Testing if a block in a Twig template exists
Published on 2021-05-22 • Modified on 2021-05-22
In this snippet, we see how to test if a block in a Twig template exists. It's sometimes helpful to know if one of the parent templates has defined a block or not. We can do precisely the same that we do to test a variable. It wasn't possible before the 2 Twig version. Of course, the example would be more relevant in a template extending another one; that's not the case in this demo template.
{% trans_default_domain 'snippet' %}
{% block defined_in_demo %}{% endblock %}
{% if block('defined_in_demo') is defined %}
<h3>{{ 'is_defined_148'|trans({'%block%':'defined_in_demo'}) }} ✅</h3>
{% else %}
<h3>{{ 'is_not_defined_148'|trans({'%block%': 'defined_in_demo'}) }} ❌</h3>
{% endif %}
{% if block('foo_bar') is defined %}
<h3>{{ 'is_defined_148'|trans({'%block%': 'foo_bar'}) }} ✅</h3>
{% else %}
<h3>{{ 'is_not_defined_148'|trans({'%block%': 'foo_bar'}) }} ❌</h3>
{% endif %}
HTML demo of the snippet
The bloc "defined_in_demo" is defined! ✅
The bloc "foo_bar" is NOT defined! ❌
More on Stackoverflow Read the doc Random snippet