1

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.

user3507003
  • 359
  • 4
  • 17

2 Answers2

3

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

tsega
  • 856
  • 2
  • 15
  • 31
user3507003
  • 359
  • 4
  • 17
0

Including templates does not mean u are importing said blocks inside the template. This mean only the block menu will exists inside child.twig.

In your first example you are actually just overwriting the block menu and creating a new block menu_country inside of it.

In your second example, you are telling twig to output the default content of the block menu and append a new block menu_country to it.


A possible solution would be to change set-up to this e.g.

menu.twig

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

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

menu-country.twig

<ul class="country">
{% for country in menu_country|default(dropdownland) %}
    <li><a href="#">{{ country }}</a></li>
{% endfor %}
</ul>

child.twig

{% extends "base.twig" %}

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

demo

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Thanks a lot for the input. Indeed it clarified some things, but i found a more proper may to solve this for my case. Embed was the keyword. – user3507003 Jan 16 '20 at 11:08