django - Django 模板系统中的 bool 逻辑

标签 django django-templates

如果您将上下文变量(例如“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 , FalseNone作为对应的 Python 对象,所以 {% if woot == True %}将评估为 False .

在早期版本的 Django 中,woot 都没有。也不是 True变量存在于模板上下文中。表达式 None == None计算结果为 True , 是的!被陈列

关于django - Django 模板系统中的 bool 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14770270/

相关文章:

django - 如何在 Django for 循环模板中获取奇数和偶数值?

python - 在 Django 中为单个产品创建页面

jquery - twitter bootstrap 下拉列表在 django 模板中不起作用

Django 管理员 : Detect if a subset of an object fields has changed and which of them

python - Django 中的完整性错误,其中项目有两个用户表?

python - 当使用最小最大范围时,Django 对象过滤器收到一个简单的日期时间,而时区支持处于事件状态

xml - 我可以在 Django 中使用 XSLT 吗?

django QueryDict 仅返回列表的最后一个值

javascript - 使用 ajax 和基于类的 View 处理引导模式中的表单提交

Django,如何将变量传递给平面页面?