如果您将上下文变量(例如“woot”)设置为 None 或只是将其保留为未定义....
{% if woot %} Yeah! {% endif %}
做你所期望的(没有)。但如果你这样做:
{% if woot == True %} Yeah! {% endif %}
它会打印“是的!”即使woot是无/未定义的。这似乎非常不直观。显然,我可以解决这个问题……但我想了解根本原因。任何想法为什么会发生......?
证明:
from django.template import Context, Template
x = Template("{% if woot %}Yeah!{% endif %}")
y = Template("{% if woot == True %}Yeah!{% endif %}")
x.render( Context( {} )) # => u''
y.render( Context( {} )) # => u'Yeah!'
x.render( Context( {'woot':None} )) # => u''
y.render( Context( {'woot':None} )) # => u'Yeah!'
这是在 Django 1.4.3 上
最佳答案
在 Django 1.5 ( release notes ) 中,模板引擎解释 True
, False
和 None
作为对应的 Python 对象,所以 {% if woot == True %}
将评估为 False
.
在早期版本的 Django 中,woot
都没有。也不是 True
变量存在于模板上下文中。表达式 None == None
计算结果为 True
, 是的!被陈列
关于django - Django 模板系统中的 bool 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14770270/