小编Tra*_* D.的帖子

Django模板系统中的布尔逻辑

如果你将一个上下文变量(例如'woot')设置为None或者只是将其保留为undefined ....

{%if woot%}是的!{% 万一 %}

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

{%if woot == True%}是的!{% 万一 %}

它将打印"是啊!" 即使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!'
Run Code Online (Sandbox Code Playgroud)

这是在Django 1.4.3上

django django-templates

4
推荐指数
1
解决办法
1134
查看次数

标签 统计

django ×1

django-templates ×1