【发布时间】:2010-07-15 19:36:17
【问题描述】:
如何区分 django 模板中的 None 和 False?
{% if x %}
True
{% else %}
None and False - how can I split this case?
{% endif %}
【问题讨论】:
标签: python django templates if-statement
如何区分 django 模板中的 None 和 False?
{% if x %}
True
{% else %}
None and False - how can I split this case?
{% endif %}
【问题讨论】:
标签: python django templates if-statement
每个 Django 模板上下文 contains True, False and None。对于 Django 1.10 及更高版本,您可以执行以下操作:
{% if x %}
True
{% elif x is None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}
Django 1.9 及更早版本不支持if 标记中的is 运算符。大多数情况下,可以使用{% if x == None %} 代替。
{% if x %}
True
{% elif x == None %}
None
{% else %}
False (or empty string, empty list etc)
{% endif %}
使用 Django 1.4 及更早版本,您无法在模板上下文中访问 True、False 和 None,您可以改用 yesno 过滤器。
在视图中:
x = True
y = False
z = None
在模板中:
{{ x|yesno:"true,false,none" }}
{{ y|yesno:"true,false,none" }}
{{ z|yesno:"true,false,none" }}
结果:
true
false
none
【讨论】:
您可以创建自定义过滤器:
@register.filter
def is_not_None(val):
return val is not None
然后使用它:
{% if x|is_not_None %}
{% if x %}
True
{% else %}
False
{% endif %}
{% else %}
None
{% endif %}
当然,你也可以调整过滤器来测试你喜欢的任何条件......
【讨论】:
对先前答案的增强可能是:
{% if x|yesno:"2,1," %}
# will enter here if x is True or False, but not None
{% else %}
# will enter only if x is None
{% endif %}
【讨论】:
yesno 过滤器中的第三个参数如果x 为None,你就会得到它。
使用True、False、None 常量创建 context_processor(或使用 django-misc 模块 misc.context_processors.useful_constants)并使用 {% if x == None %} 或 {% if x == False %}
context_processor.py:
def useful_constants(request):
return {'True': True, 'False': False, 'None': None}
【讨论】:
这是另一个棘手的方法:
{% if not x.denominator %}
None
{% else %}
{% if x %}
True
{% else %}
False
{% endif %}
{% endif %}
那是因为“无”没有属性“分母”,而“真”和“假”都是1。
【讨论】: