django 模板如果条件 [英] django template if condition

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

问题描述

这里有一个问题.

我有以下内容

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

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

form.tpl.yes_no_required 的值为 None,但我被路由到路径 2.谁能解释一下为什么会这样?如果值为无,我不希望它显示任何内容.

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? if the value is none, i do not want it display anything.

推荐答案

您不能使用模板语言来测试您认为是常量的内容,解析器实际上正在测试 2 个文字".

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

解析器测试名称为None"和False"的 2 个文字.当解析器尝试在上下文中解析这些时,会抛出 VariableDoesNotExist 异常并且两个对象都解析为 python 值 None和无 == 无.

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)

打印你''

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

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