django template if condition

一个人想着一个人 提交于 2019-12-19 02:48:18

问题


got a question here.

I have the following

{% if form.tpl.yes_no_required == True  %}
             <!-- path 1 -->
{% else %}
    {% if form.tpl.yes_no_required == False %}

        <!-- path 2 -->
    {% endif %} 
{% endif %}

The value for form.tpl.yes_no_required is None, but I was routed to path 2. Can anyone please explain why is this so? EDIT: if the value is none, i do not want it display anything.


回答1:


You can't use the template language to test against what you think are constants, the parser is actually testing 2 "literals".

The parser tests for 2 literals with names 'None' and 'False'. When parser tries to resolve these in the context a VariableDoesNotExist exception is thrown and both objects resolve to the python value None and None == None.

from django.template import Context, Template
t = Template("{% if None == False %} not what you think {% endif %}")
c = Context({"foo": foo() })

prints u' not what you think '

c = Context({'None':None})
t.render(c)

prints u' not what you think '

c = Context({'None':None, 'False':False})
t.render(c)

prints u''




回答2:


None != False None != True also ... do some things like this for none item

{% if form.tpl.yes_no_required  %}
             <!-- path 1 -->
{% else %}
    {% if not form.tpl.yes_no_required %}

        <!-- path 2 -->
    {% endif %} 
{% endif %}


来源:https://stackoverflow.com/questions/5667878/django-template-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!