gabtzi gabtzi - 4 months ago 9
Twig Question

how does "{% use %}" work in twig using symfony3?

I'm trying to use the {% use %} syntax to import the blocks from a child template in my base template as described in http://twig.sensiolabs.org/doc/tags/use.html but I'm having some issues so I'm wondering what I'm missing.

I have the following files

#base.html.twig
<!DOCTYPE html>
<html>
{% use ':admin/page:body.html.twig' %}
</html>





#admin/page/body.html.twig
{% block contentBody %}
<body>
<p>Test Body</p>
</body>
{% endblock %}


and finally

#default/index.html.twig
{% extends base.html.twig %}

{% block contentBody %}
<body>
<p>Test ContentBody</p>
</body>
{% endblock %}


As I understand it according to the documentation the first two files are almost as if I declared one

#base.html.twig
<!DOCTYPE html>
<html>
{% block contentBody %}
<body>
<p>Test Body</p>
</body>
{% endblock %}
</html>


My controller renders default/index.html.twig

Using the first 3 files together yields a blank page although I would think it should render "Test ContentBody"

If I replace the base.html.twig contents with the last snippet it works as it should and renders "Test ContentBody"

If I replace the use command with include it yields "Test Body" as expected

If anyone could explain to me what I'm doing wrong or steer me in the right direction as to what I'm missing in the documentation I would really appreciate it. Thanks in advance

PS: I've also tried to just declare the block in admin/page/body.html.twig
like this

#admin/page/body.html.twig
{% block contentBody %}{% endblock %}


in case it breaks because of the part in the documentation that says when you "use" templates they should not have a body but it didn't help.

NDM NDM
Answer

Importing blocks with use does not output them automatically, so you still have to define them in your base template:

#base.html.twig
<!DOCTYPE html>
<html>
    {% use ':admin/page:body.html.twig' %}
    {% block contentBody %}
        parent()
    {% endblock %}
</html>

the use is mostly intended for reusing blocks with the block() function.