Django模板系统中的布尔逻辑

时间:2013-02-08 10:16:42

标签: django django-templates

如果您将上下文变量(例如'woot')设置为None,或者只是将其保留为未定义....

  

{%if woot%}是的! {%endif%}

你期望什么(没什么)。但如果你这样做:

  

{%if woot == True%}是的! {%endif%}

它将打印“是啊!”即使woot是None / undefined。这似乎非常不直观。显然,我可以解决这个问题......但我想了解根本原因。任何想法为什么会发生....?

证明:

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上

1 个答案:

答案 0 :(得分:5)

在Django 1.5(release notes)中,模板引擎将TrueFalseNone解释为相应的Python对象,因此{% if woot == True %}将评估为False

在早期版本的Django中,模板上下文中不存在wootTrue变量。表达式None == None的计算结果为True,因此显示是的!

相关问题