如何使用Django模板语法判断变量是否为False?
{% if myvar == False %}
似乎不管用.
请注意,我非常明确地想判断它是否具有Python值False
.这个变量也可以是一个空数组,这就是我要判断的not.
如何使用Django模板语法判断变量是否为False?
{% if myvar == False %}
似乎不管用.
请注意,我非常明确地想判断它是否具有Python值False
.这个变量也可以是一个空数组,这就是我要判断的not.
Django 1.10(release notes)在if
标记中添加了is
和is not
比较运算符.此更改使模板中的身份测试变得非常简单.
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 (release notes)版开始,模板引擎将True
、False
和None
解释为相应的Python对象.
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'