Django templates: If false?

后端 未结 10 1150
灰色年华
灰色年华 2020-12-23 14:43

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

{% if myvar == False %}

Doesn\'t seem to work.

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 15:06

    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'
    

    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'
    

提交回复
热议问题