user4383363
user4383363

Reputation:

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.

Upvotes: 13

Views: 46016

Answers (1)

lxg
lxg

Reputation: 13107

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.

Upvotes: 13

Related Questions