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

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

问题描述

如何使用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 标签。这个变化使得模板中的身份测试很简单。

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'



<一个href =https://docs.djangoproject.com/en/1.8/releases/1.5/#minor-features =nofollow noreferrer>(发行说明)模板引擎解释 True False None 作为相应的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'

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

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

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