How can I conditionally override a TWIG layout blo

2020-08-09 05:37发布

问题:

First, let me start with the code I'm attempting to use:

{% if modal == true %}
    {% block header %}{% endblock %}
    {% block footer %}{% endblock %}
{% endif %}

What I'm trying to accomplish is to not show my header and footer blocks ONLY if the variable called modal is true. I also have this below the if statement:

{% block content %}
    {{ dump(modal) }}
{% endblock %}

What happens here is that my override for emptying the header and footer blocks always runs regardless of if the value of modal is true or otherwise. So, I run this with modal passed in as false and the result is that the header and footer still don't show. The output of the dump command accurately shows true or false, but the condition always seems to evaluate to true in the if statement.

Can blocks not be wrapped in a conditional statement, or is there something additional I need to do to make this work?

Thanks for any help you can offer.

回答1:

Blocks don't care about any logic around it, as said in the documentation:

A block provides a way to change how a certain part of a template is rendered but it does not interfere in any way with the logic around it.

You should put that logic inside the block, not on the outerside, as you can see on the last example in that article.



回答2:

Define

{% block footer %}Some standard content{% endblock %}

in parent twig template. Then in template where you want to decide if display content of footer you can do:

{% block footer %}
  {% if not modal == true %}
    {{ parent() }}
  {% endif %}
{% endblock %}

If the modal is true - footer will be empty, if not - in footer will be printed "Some standard content"