Symfony2: how to share js libs and css between packages

I have different Bundles: MainBundle (Home page), SecurityBundle (Login, Registration), MessageBundle (Message system), ShopBundle.

I also follow the three-stage layout scheme (:: base.html.twig, AcmeMainBundle :: layout.html.twig, AcmeMainBundle: default: index.html.twig).

But I have problems with sharing js libraries through the application (e.g. jquery) and the definition of base.css (which sets some base classes, backgrounds, fonts, etc.)

So what is the best approach to using common css and js withouth that should lose support on the team?

One idea would be to create a CommonBundle that contains all the global js and css and some layout files, but I don't think this is the best way to handle this ...

+4
source share
2 answers

If you want to share common assets between all your packages, the best choice is to place them in the app/Resources/public directory. For instance:

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

You can then reference them in your layout as follows:

 {% 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 %} 

Note. As you can see, for regular libraries like jQuery, the best choice is to use the shared cached version hosted by Google. This practice can speed up the response time of your application.

+17
source

Using the recent version of Symfony (2.5), I saw that fsenart's answer did not work in my case. Instead, I put the shared folder with the shared content in a web folder:

 web/public --js --css 

Then, to use it in the main layout, the following code works:

 {% block javascripts %} {% javascripts 'public/js/*' %} <script type="text/javascript" src="{{ asset_url }}"></script> {% endjavascripts %} {% endblock %} 

But for this you need to remember to call the Twig parent () function when using the javascript block in the child layout.

0
source

All Articles