Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template if condition

got a question here.

I have the following

{% if form.tpl.yes_no_required == True  %}
             <!-- path 1 -->
{% else %}
    {% if form.tpl.yes_no_required == False %}

        <!-- path 2 -->
    {% endif %} 
{% endif %}

The value for form.tpl.yes_no_required is None, but I was routed to path 2. Can anyone please explain why is this so? EDIT: if the value is none, i do not want it display anything.

like image 387
goh Avatar asked Apr 14 '11 18:04

goh


People also ask

How do you do if statements in Django?

How to use if statement in Django template. In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.

Is equal in Django template?

If the values of these variable are equal, the Django Template System displays everything between the {% ifequal %} block and {% endifequal %}, where the {% endifequal %} block marks the end of an ifequal template tag.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


1 Answers

You can't use the template language to test against what you think are constants, the parser is actually testing 2 "literals".

The parser tests for 2 literals with names 'None' and 'False'. When parser tries to resolve these in the context a VariableDoesNotExist exception is thrown and both objects resolve to the python value None and None == None.

from django.template import Context, Template
t = Template("{% if None == False %} not what you think {% endif %}")
c = Context({"foo": foo() })

prints u' not what you think '

c = Context({'None':None})
t.render(c)

prints u' not what you think '

c = Context({'None':None, 'False':False})
t.render(c)

prints u''

like image 147
Jason Culverhouse Avatar answered Nov 15 '22 09:11

Jason Culverhouse