Skip to content

conditionally define a block in twig 2 #2393

Description

@matthbull

hi all,

twig 2.1

symfony3

Ive asked this on SO, but the only answer I have sort of confirms my suspicions, but I'd just like to check with you guys if this is actually the case.

I want to conditionally define a block in a twig template, as in the example below:

** called template **

{% extends 'base.html.twig' %}
{% set something = true %}
{% if not something %}
    {% block left_sidebar %}
        <h2>sidebar rendered</h2>
    {% endblock %}
{% endif %}

** base.html.twig **

{% if block('left_sidebar') is defined %}
   {{ block('left_sidebar')|raw }}
{% else %}
    no block
{% endif %}

I have a use case where I dont actually want to define the block if its not needed (dynamic regions in the base template).

The problem is, the block always renders, regardless of a true/false result of the conditional check. But this only seems to happen if the template is extending another. Is this because of compile order? Or am I missing something.

Heres a fiddle to illustrate.

thanks in advance.

Matt

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions