Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include JavaScript files into twig template using Symfony2

I can easily include CSS files into my twig template like this:

{% 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 tried to use assetics too, but that didn't work either.

like image 576
fermoga Avatar asked Aug 23 '15 19:08

fermoga


People also ask

Can you put Javascript in twig?

js Twig tag is essential to using JS in Twig. It takes JS code passed to it and appends it at end of the template, right before ending body tag. Multiple js tags can be used - content from each of them will be concated with the rest. You don't need to wrap code passed to js into <script> tags - js will do that for you.


1 Answers

I'd recommend the Assetic approach. It's not exactly simple, but it gives you huge benefits.

First, embed your JS in a template like this:

{% 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 you like.

Now run the following on the command line:

app/console assetic:dump

In your dev environment, this will generate a copy of your JS files within the document root. In your prod, this will generate one combined file in the doc root – the first benefit.

To have your files generated automatically in the background while you edit them, run the following from the command line, and keep it running until you're done (cancel then with Ctrl+C):

app/console assetic:watch --force

(The --force option causes Assetic to generate the files even if it there don't seem to be any modifications.)

Another benefit is the filter='uglifyjs2' statement: It causes the files to be "compressed" with UgilifyJS, which loads much faster.

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

like image 86
lxg Avatar answered Oct 10 '22 04:10

lxg