Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I conditionally override a TWIG layout block?

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.

like image 837
slave2zeros Avatar asked Feb 06 '13 21:02

slave2zeros


2 Answers

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"

like image 73
nataliastanko Avatar answered Sep 19 '22 04:09

nataliastanko


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.

like image 24
Wouter J Avatar answered Sep 22 '22 04:09

Wouter J