Answer: Conditional blocks in twig

Somebody asked a StackOverflow question about conditionally outputting blocks. I had a similar need. I came up with a solution that fit my need and responded with the answer:

The block() function appears to return a falsey value if nothing or only white space was output in it, so you can wrap the block in a truthiness test and in the child template make sure it is empty if you don’t want it to show. Something like this worked for me:

base.html.twig:

{% if block('left_sidebar') %}
    <div class="col-md-2">
        {% block left_sidebar %}{% endblock %}
    </div>
    <div class="col-md-10">
{% else %}
    <div class="col-md-12">
{% endif %}

index.html.twig:

{% block left_sidebar %}
    {% if not is_granted('IS_FULLY_AUTHENTICATED') %}
        {% include ':blocks:block__login.html.twig' %}
    {% endif %}
{% endblock %}

Published by

Toby

I am a quiet person from Northeast Ohio. I work as a web developer. I like computers, music, and many other things.

Leave a Reply

Your email address will not be published. Required fields are marked *