Django 模板:如果为假? [英] Django templates: If false?

查看:17
本文介绍了Django 模板:如果为假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Django 模板语法检查变量是否为 False?

How do I check if a variable is False using Django template syntax?

{% if myvar == False %}

似乎不起作用.

请注意,我特别想检查它是否具有 Python 值 False.这个变量也可以是一个空数组,这不是我想要检查的.

Note that I very specifically want to check if it has the Python value False. This variable could be an empty array too, which is not what I want to check for.

推荐答案

Django 1.10 (发行说明)if 标签中添加了 isis not 比较运算符.此更改使模板中的身份测试变得非常简单.

Django 1.10 (release notes) added the is and is not comparison operators to the if tag. This change makes identity testing in a template pretty straightforward.

In[2]: from django.template import Context, Template

In[3]: context = Context({"somevar": False, "zero": 0})

In[4]: compare_false = Template("{% if somevar is False %}is false{% endif %}")
In[5]: compare_false.render(context)
Out[5]: u'is false'

In[6]: compare_zero = Template("{% if zero is not False %}not false{% endif %}")
In[7]: compare_zero.render(context)
Out[7]: u'not false'

如果您使用的是旧版 Django,则从 1.5 版开始 (发行说明) 模板引擎将 TrueFalseNone 解释为相应的 Python 对象.

If You are using an older Django then as of version 1.5 (release notes) the template engine interprets True, False and None as the corresponding Python objects.

In[2]: from django.template import Context, Template

In[3]: context = Context({"is_true": True, "is_false": False, 
                          "is_none": None, "zero": 0})

In[4]: compare_true = Template("{% if is_true == True %}true{% endif %}")
In[5]: compare_true.render(context)
Out[5]: u'true'

In[6]: compare_false = Template("{% if is_false == False %}false{% endif %}")
In[7]: compare_false.render(context)
Out[7]: u'false'

In[8]: compare_none = Template("{% if is_none == None %}none{% endif %}")
In[9]: compare_none.render(context)
Out[9]: u'none'

尽管它不像人们预期的那样工作.

Although it does not work the way one might expect.

In[10]: compare_zero = Template("{% if zero == False %}0 == False{% endif %}")
In[11]: compare_zero.render(context)
Out[11]: u'0 == False'

这篇关于Django 模板:如果为假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆