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:


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


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