How to check if a block exists in a twig template - Symfony2

You can solve it like this, if you want to display a certain block only if it has content. Hope, this is what you're looking for.

Example index.html.twig

{% set _block = block('dynamic') %}
{% if _block is not empty %}
    {{ _block|raw }}
{% endif %}

Example part.html.twig

{% extends "index.html.twig" %}

{% block dynamic %}
    Block content goes here.
{% endblock %}

You can do it like this:

{% if block('posLeft') %}
  ...
{% endif %}

But it is not efficient if you need output of rendered block. So if you will need block output you should assign it to variable in the first place and then do assertions


The other answers here do not work for twig 2.1 (I've not tested on ~2.0), so here's a small update:

{% if block('dynamic') is defined %}
    {{ block('dynamic')|raw }}
{% endif %}

Note that the line to render the block is not:

{% block dynamic %}
    {#  this wont work  #}
{% endblock %}

This wont work because the block will be rendered during compile, and so the test will return true that it exists (as its tested at runtime). So you need to render the block with {{ block('dynamic')|raw }} instead as this doesn't actually define the block in the template.


First check, which Twig version you are using inside your Symfony project, because the answers here are only for Twig 1.

If you are using Twig 2 you are lucky. According to the Twig documentation, you can use the defined test to check if the block exists in the current template context.

{% if block("dynamic") is defined %}
   ...
{% endif %}

I have written a little TwigExtension to check if the block gets called inside the if statement and it seems like Twig only really checks if the block exists and does not call it.

The link to the docs: https://twig.symfony.com/doc/2.x/functions/block.html

If you are using Twig 1, the old answer at https://stackoverflow.com/a/13806784/6458657 is still correct.