Symfony 2: Using asset inheritance in Twig

Yesterday I came up with the following problem: I wanted to add a javascripts-block in my layout. This block should be extended in a child template. Using Assetic this should be easy and plain simple. Well, in theory…

It did not. But the cause wasn’t really clear to me until. Let’s illustrate my problem with an example:

{# layout.html.twig #}
{% block javascripts %}
    {% javascripts '@AcmeTestBundle/Resources/public/js/jquery.min.js'%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}
{# test.html.twig #}
{% extends 'AcmeTestBundle:layout.html.twig' %}
{% block javascripts %}
    {% javascripts '@AcmeTestBundle/Resources/public/js/plugin.js'%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

I was expecting that these two blocks would result in two distinct javascript-links but it didn’t. In fact the second block just overwrote the first block causing JS-errors. The solution was pretty simple:

{# test.html.twig #}
{% extends 'AcmeTestBundle:layout.html.twig' %}
{% block javascripts %}
    {{ parent() }}
    {% javascripts '@AcmeTestBundle/Resources/public/js/plugin.js'%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

Enter the parent()-function. This function renders the parent-block and puts the rendered content in the current block. The result is the correct built javascript. Enjoy.

0 Responses to “Symfony 2: Using asset inheritance in Twig”


  • No Comments

Leave a Reply