Learn how to use multiple times a block in twig.

To repeat a block that already exists (and we won't declare for any reason twice, not even with different names) we need to use the block function.

block function

Normally if you try to write twice a block, using for example :

{# Base file#}
{% block something %}{% endblock %}

{# content on a child template #}
{% block something %}{% endblock%}

You'll get the following message the block 'something' has already been defined in "::layout.html.twig".

If a template uses inheritance and you need to print a block multiple times, the block function is what you need to use :

{{ block('theNameOfTheBlockThatYouWantToRepeat') }}

Now for example, if you have a block named title which is replaced in every view. And you want not only the content inside the <title> tag but in a <h1> tag too, then you can use :

{% block title %}{% endblock %}

{# Repeat the content of title inside the following tag too#}
<h1>{{ block('title') }}</h1>


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors