Symfony framework. Templates. Assets. Assetic. Stylesheets (Lesson 8. Assets and Twig)

So, in the previous lesson we learned how to use the Twig template engine in the Symfony framework. Now we know how to write a simple template. But we don't know how to include external components (stylesheets, js, images), as well as create links to our own pages. Let's start with the latter. To do this, you need to call the path() function, its arguments are the route name and (optionally) an array of parameters.

<a href="{{path('my_route')}}">Link</a>
The parameters are set as follows:
<a href="{{path('my_route', {'parameter': 'value'})">Link</a>
To include these components, the Symfony framework uses Assets. The default directory for Assets is PathToBundle/public. Here you can find directories for css, js, and images. In the simplest case, including a css file is done using the asset() function, which will create the actual path:
{% block stylesheets %}
   <link href="{{ asset('/css/main.css') }}" type="text/css" rel="stylesheet" />
{% endblock %}
Images and js are also included in the same way. But sometimes you may need to include all the contents of a directory (like the same stylesheets or js). Of course, in that case, you can include each file separately (as described above). But there is another way to do it (using assetic):
{% stylesheets 'bundles/MyPortal/css/*' %}
    <link rel="stylesheet" href="{{ asset_url }}"/>
{% endstylesheets %}
This way, all the contents of the directory will be included. Just don't forget to install the assets:
php app/console assets:install
If possible, it will be much more convenient to develop by installing assets in symlink mode:
php app/console assets:install --symlink
In this case, you won't have to reinstall every time the contents in the development directory is changed.

If you are moving to production build, don't forget to do

php app/console assetic:dump --env=prod --no-debug
That seems to be all - now we know how to use templates in Symfony framework.