phptemplatestwigextending

Replace only one nested block in twig


I have the following twig structure:

base.twig

<html>
  <head>
  </head>

  <body class="fade-in {{body_class}}">
    <main>
      {% block menu %}
          {% include 'menu.twig' %}
      {% endblock %}
    </main>
  </body>
</html>

menu.twig

<header>
  <div>
    {% block menu_main %}
       {% include 'menu-main.twig' %}
    {% endblock %}

    {% block menu_country %}
        {% include 'menu-country.twig' with { menu_country: dropdownland } %}
    {% endblock %}
  </div>
</header>

child.twig

{% extends "base.twig" %}

{% block menu %}
  {% block menu_country %}
    {% include 'menu-country.twig' with { menu_country: menu_ap_countries } %}
  {% endblock %}
{% endblock %}

What i want to achieve is, just replace the block menu_country inside child.twig. If i use the approach above, the whole block menu gets replaced by only menu_country which means that the block menu_main is missing.

I tried also

{% extends "base.twig" %}

{% block menu %}
  {{ parent() }}
  {% block menu_country %}
    {% include 'menu-country.twig' with { menu_country: menu_ap_countries } %}
  {% endblock %}
{% endblock %}

but this renders the block menu_country twice. Is there any way to achieve this?

Thanks a lot.


Solution

  • After further investigation due to @DarkBees answer, i came accross the embed function which does exactly what i need in this case. So the extending template becomes this:

    {% block menu %}
      {% embed 'menu.twig'%}
        {% block menu_country %}
          {% include 'menu-country.twig' with { menu_country: menu_ap_countries } %}
        {% endblock %}
      {% endembed %}
    {% endblock %}
    

    By embedding, I am able to overwrite the block inside menu.twig