Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my condition logic work as expected in Jinja2/CherryPy?

{% if bCat2 == True %}
    <div>True</div>
{% else %}
    <div>False</div>

Returns <div>False</div> even when bCat2 is True. Thanks, Andrew

like image 838
Andrew Kloos Avatar asked Dec 08 '11 15:12

Andrew Kloos


4 Answers

This part of documentation can help you:

The special constants true, false and none are indeed lowercase. Because that caused confusion in the past, when writing True expands to an undefined variable that is considered false, all three of them can be written in title case too (True, False, and None). However for consistency (all Jinja identifiers are lowercase) you should use the lowercase versions.

Source: http://jinja.pocoo.org/docs/templates/

Try that code:

{% if bCat2 == true %}
<div>True</div>
{% else %}
<div>False</div>
{% endif %}
like image 77
Evgeni Nabokov Avatar answered Sep 21 '22 21:09

Evgeni Nabokov


Option 1: Most common solution

Solve that like python do.

Check if variable is true

{% if bCat2 %}
    <div>True</div>
{% else %}
    <div>False</div>

Check if variable is false

{% if not bCat2 %}
    <div>False</div>
{% else %}
    <div>True</div>

Jinja2 If documentation

Option 2: Jinja2 sameas solution

Solve like jinja2 do. Becareful with boolean lowercase.

Check if variable is true

{% if bCat2 is sameas true %}
    <div>True</div>
{% endif %}

Check if variable is false

{% if bCat2 is sameas false %}
    <div>False</div>
{% endif %}

Jinja2 sameas documentation

like image 34
mrroot5 Avatar answered Sep 22 '22 21:09

mrroot5


The proper way to do this in Jinja2 is:

{% if bCat2 is sameas true %}
    <div>True</div>
{% elif bCat2 is sameas false %}
    <div>False</div>
{% endif %}

The reason why you cannot do

{% if bCat2 == true %}

is that if bCat2 == 1 or bCat2 == 1.0 it will also be considered True.

like image 13
Dag Wieers Avatar answered Sep 24 '22 21:09

Dag Wieers


To test a Boolean variable in a template, convert it to a string in Python

str(bCat2)

and then compared it to a string in the template

{% if bCat2 == 'True' %}
    <div>True</div>
{% else %}
    <div>False</div>
like image 11
Andrew Kloos Avatar answered Sep 24 '22 21:09

Andrew Kloos