Raphael Riel
Raphael Riel

Reputation: 199

Nested blocks across template hierarchy‎ in Twig

I have a view view.twig that extends template_child.twig which in turn extends template_base.twig :

I want to be able to nest each block within another, without creating a "sub_content" block that will only work when extending template_child. So view.twig could extends either template without the need to rename the block directive.

view.tig:

{% extends "template_child.twig" %}
{% block content %}
    Stuff that should go in "content"
{% endblock content %}

template_child.tig:

{% extends "template_base.twig" %}
{% block content %}
    <div id="styling-of-content">
        {% block content %}
        {% endblock content %}
    </div>
    Stuff that absolutely needs to be after "content"
{% endblock content %}

template_base.tig:

<html><body>
    {% block content %}
    {% endblock content %}
</body></html>

Currently Twig output this error when attempting to run this code:

The block 'content' has already been defined line X in "template_child.twig" at line Y

Using Twig v1.12.3

Upvotes: 1

Views: 3570

Answers (1)

dturcotte
dturcotte

Reputation: 606

It's not really possible since Twig compiles the templates in pure PHP classes and methods. In PHP child methods will always have the power to overwrite the parent methods.

The solution would be to use a sub_content block defined in view.twig that is included in the content block in "template_child.twig".

Upvotes: 2

Related Questions