Symfony2: Working with Assetic


Well, i finally took the time to read something about Assetic and let me tell you, it’s awesome. This is how it works:

    {% javascripts '@yourBundle/Resources/js/*' output='js/combined.js' %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}

The code above ( used inside a Twigg template ) will pack all the javascripts inside Resources/js folder and put them all inside a single file called combined.js inside the web/js folder.

While developing, that process will take a lot of time each time you refresh the page, that’s why you will want to call this command to make Assetic watch for changes every X time to generate a physical version of each file so the files can be served directly to the browser rather than being generated at runtime:

php app/console assetic:dump --watch

That will create a bunch of javascripts in the web/js folder, and everytime you change a file in your Resources/js it will be automatically updated in your web/js folder. So now page load times will be optimal.

Also, on production, one javascript per javascript will be generated, this is fine because this way you can debug them easily. On Development, assetic will pack all the javascript on a single file (in the case of the example above).

That’s for when you are developing. When deploying to production, you can delete all the files inside the web/js folder (generated by assetic on development) and run this command:

php app/console assetic:dump --env=prod --no-debug

That will generate the FINAL version of all the javascripts so that from now on, the browser will be served with physical javascripts and assetic will not be used anymore.

Remember that everytime you make a change on the javascripts, you will have to run the command above to generate the final version and that will be the files you will have to upload to production.

For more information go to http://symfony.com/doc/current/cookbook/assetic/asset_management.html

Advertisements