How to include javascript files in a branch template using Symfony2

I can easily include CSS files in my branch template:

{% block stylesheets %} <link rel="stylesheet" href="{{ asset('bundles/user/css/bootstrap.min.css') }}"/> <link rel="stylesheet" href="{{ asset('bundles/user/css/bootstrap-theme.min.css') }}"/> <link rel="stylesheet" href="{{ asset('bundles/user/css/main.css') }}"/> {% endblock %} 

But for my javascript files

 {% block javascripts %} <script src="{{ asset('bundles/user/js/jquery-1.11.3.min.js') }}"></script> <script src="{{ asset('bundles/user/js/bootstrap.min.js') }}"></script> {% endblock %} 

The approach does not work. I also tried using assetics , but that didn't work either.

+5
source share
1 answer

I would recommend the Assetic approach. It is not quite simple, but it gives you enormous advantages.

First insert your JS into the template as follows:

 {% block my_javascripts %} {% javascripts '@FooBarBundle/Resources/public/js/foo.js' '@FooBarBundle/Resources/public/js/bar.js' filter='?uglifyjs2' %} <script src="{{ asset_url }}" type="text/javascript"></script> {% endjavascripts %} {% endblock %} 

Add as many JS files as possible.

Now run the following command at a command prompt:

 app/console assetic:dump 

In your dev environment, this will create a copy of your JS files in the document root. In your prod this will create one merged file at the root of the doc - the first advantage.

To have your files generated automatically in the background while editing them, run the following on the command line and continue to work until you are done (then cancel with Ctrl + C ):

 app/console assetic:watch --force 

(The --force option causes Assetic to generate files, even if there are no changes.)

Another advantage is the expression filter='uglifyjs2' : it makes the files β€œcompress” using UgilifyJS, which loads much faster.

Learn more about using Assetic for JS and CSS in Symfony2 in the cookbook.

+10
source

All Articles