如果您将上下文变量(例如“woot”)设置为 None 或者只是将其保留为未定义......
{% if woot %} 是的!{% 万一 %}
做你所期望的(没有)。但如果你这样做:
{% if woot == True %} 是的!{% 万一 %}
它将打印“是的!” 即使 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 上