Multiple extension of layout in twig/php

php, twig

Solution

You need to use "Use" - pun not intended! :-)

main.twig
<html><body>
{% block a %}{% endblock %}
{% block b %}{% endblock %}
</body></html>

replacea.twig
{% block a %}hello{% endblock %}

replaceb.twig
{% extends "main.twig" %}
{% use "replacea.html" %}
{% block b %}world{% endblock %}

Check out the documentation: https://twig.symfony.com/doc/tags/use.html

Problem

I have a problem figuring out how to solve the following issue with Twig templates I have a system where two parts wants to change blocks in the layout without know each other. The idea of my templates are ``` main.twig <html><body> {% block a %}{% endblock %} {% block b %}{% endblock %} </body></html> replacea.twig {% extends "main.twig" %} {% block a %}hello{% endblock %} replaceb.twig {% extends "main.twig" %} {% block b %}world{% endblock %} ``` My problem is that I do not know how to achieve this, as the places where I call replacea and replaceb only shares a "viewengine" so I am able to collect all render calls and bulk them. My first idea to solve this was to extend a variable, say "layout", but then when I call render layout would be replaced with the same in all templates and not with "replacea.twig" in replaceb and with "main.twig" in replacea. Hope you understand my problem.

Original source