Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 - how to put a block in an if statement?

I am trying to use an if to determine which block should fill my {% block content %}.

I have a base.html which has a default {% block content %} and this template is extending base.html. So I tried this:

{% extends "base.html" %} {% if condition == True %}     {% block content %}     <div>blah blah blah blah</div>     {% endblock content %} {% endif %} 

and I was expecting to see blah blah blah blah if condition was true and see the default block if it wasn't true.

But both times I got blah blah blah blah.

Then I tried this one:

{% extends "base.html" %} {% if condition == True %}     {% block content %}     <div>blah blah blah blah</div>     {% endblock content %} {% else %}     {% block content %}     <div>The Default Thing</div>     {% endblock content %} {% endif %} 

and I got this error:

TemplateAssertionError: block 'content' defined twice 

How can I put a block inside an if statement?

like image 924
Taxellool Avatar asked Mar 26 '14 08:03

Taxellool


People also ask

How do you write an if statement in Jinja?

In-line conditional statements​ Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.

What is block content in Jinja?

All the block tag does is tell the template engine that a child template may override those placeholders in the template. In your example, the base template (header. html) has a default value for the content block, which is everything inside that block. By setting a value in home.


1 Answers

You cannot make a {% block %} conditional; once you use the tag, the block is always going to be filled in.

Put your conditional inside the block instead, and use super() to instruct Jinja to use the original contents of the block as defined in the template:

{% extends "base.html" %} {% block content %}     {% if condition %}         <div>blah blah blah blah</div>     {% else %}         {{ super() }}     {% endif %} {% endblock content %} 
like image 88
Martijn Pieters Avatar answered Sep 20 '22 14:09

Martijn Pieters