Symfony2: How to share js libs and css between bundles

assetic, assets, symfony

Solution

If you want to share common assets among all your bundles, the best choice is to place them in the `app/Resources/public` directory. For example:

app/Resources/Public
|-- css
|   `-- base.css
|-- js
|   `-- jquery.js

Then you can reference them in your layout as follow:

{% block stylesheets %}
  {% stylesheets '../app/Resources/public/css/*' %}
    <link rel="stylesheet" type="text/css" charset="UTF-8" media="all" href="{{ asset_url }}"/>
  {% endstylesheets %}
{% endblock %}

{% block javascripts %}
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  {% javascripts '../app/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
  {% endjavascripts %}
{% endblock %}

Remark: As you can see, for common libraries like jQuery, the best choice remains the use of common cached version hosted at Google. This kind of practice can speedup your application response time.

Problem

I have different Bundles: MainBundle (Homepage), SecurityBundle (Login, Registration), MessageBundle (Message System), ShopBundle. I also follow the three stage layout schema (::base.html.twig, AcmeMainBundle::layout.html.twig, AcmeMainBundle:Default:index.html.twig). But I have problems sharing common js libaries through the application (e.g. jquery) and defining a base.css (which sets some base classes, backgrounds, fonts etc.) So whats the best approach to use shared css and js withouth having to lose assetic support? One idea would be to create a CommonBundle which holds all global js and css and some layout files but I don't think this is the best way to handle this...

Original source

Related problems