Using assetic in the Symfony framework

A few notes back I considered working with assets in the Symfony framework. This example shows how to work with your own assets. But in practice, it is often necessary to use external assets.

For such, and not only such tasks, assetic is suitable. It is quite difficult to describe in a few words what it is. But I imagine assetic as an asset manager for myself.

Sometimes it is simply impossible to do without it. For example, if we connect something with an external bundle, for example, Twitter Bootstrap (twbs/bootstrap in Composer). All content is located in a non-accessible place (as you probably know, for security reasons, everything except the web folder (or its equivalent) is closed for external access).

In this case, assetic allows you to transfer the necessary files to an accessible place.

To do this, you need to configure assetic:


# Assetic Configuration
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [ HarentiusSiteBundle ]

filters: cssrewrite: ~ #closure: # jar: %kernel.root_dir%/Resources/java/compiler.jar #yui_css: # jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar

assets: bootstrap_min_css: inputs: - %kernel.root_dir%/../vendor/twbs/bootstrap/dist/css/bootstrap.min.css filters: - cssrewrite output: css/bootstrap.min.css

jquery_min_js: inputs: - %kernel.root_dir%/../vendor/components/jquery/jquery.min.js output: js/jquery.min.js

bootstrap_min_js: inputs: - %kernel.root_dir%/../vendor/twbs/bootstrap/dist/js/bootstrap.min.js output: js/bootstrap.min.js

We see that we need to specify a bundle for assets (bundles section).

Then we move on to the assets configuration: it is necessary to specify a link to the asset under which it will be accessible from, for example, templates, input files (which are, for example, in a non-accessible place) and output files (in an accessible place). Filters can also be applied.

After such actions, you can use links in the template:

{% stylesheets 'css/bootstrap.min.css' %}
    <link rel="stylesheet" href="{{ asset(asset_url) }}"/>
{% endstylesheets %}
To make all this work on the production build, you need to call
php app/console assetic:dump