How to repeat an existing 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>

This could interest you

Become a more social person