I would really like to use assetic in my symfony 2 project as it has many useful features, but I'm not sure about the best way to implement the following requirement.
I have several js files that can be included in all pages. However, some of them are related only to a subset of page templates, in which I include specific templates (or also embed specific controllers), that require those specific javascript files.
Now I have the following options:
I create a block element for the javascripts in the layout and in the specific page templates (where I include the templates with javascript, e.g. templateWithComplexJs.html.twig), I overwrite this block using {{ parent() }}, as described here: Combining Assetic Resources across inherited templates.
{# ... specific.html.twig #} {% extends 'MyBundle::layout.html.twig' %} ... {% include 'MyBundle:Foo:templateWithComplexJs.html.twig' %} ... {% block javascripts %} {{ parent() }} {% javascripts '@MyBundle/Resources/public/js/specific/complex.js' %} <script src="{{ asset_url }}"></script> {% endjavascripts %} {% endblock %}
The disadvantages I see:
a) When I adapt an included template (e.g. update to a new js lib), then I have to adapt all page templates, where they are included. In a complex system that can easily lead to errors.
b) It can happen that I include a javascript twice, once in the layout's and once in the template's javascript, assetic doesn't know because they are treated separatelly.I include all js files ever needed in the layout, then I only have to change one place when I adapt the included templates and it's unlikely that I include javascripts twice.
The disadvantage I see:
As the js files can have significant size I would prefer to include them only in the few cases when I really need them.
In this related question ( Twig Assetic Stylesheets Among Several Templates ) it says that it's currently not possible with assetic to achieve a satisfying solution, but I guess that I'm not the only one having these requirements and wanting to use assetic anyway.
So, what's the best practice for that kind of scenario?