Python的Django框架中if标签的相关使用
{%if%}标签检查(evaluate)一个变量,如果这个变量为真(即,变量存在,非空,不是布尔值假),系统会显示在{%if%}和{%endif%}之间的任何内容,例如:
{%iftoday_is_weekend%}
<p>Welcometotheweekend!</p>
{%endif%}
{%else%}标签是可选的:
{%iftoday_is_weekend%}
<p>Welcometotheweekend!</p>
{%else%}
<p>Getbacktowork.</p>
{%endif%}
Python的“真值”
在Python和Django模板系统中,以下这些对象相当于布尔值的False
- 空列表([])
- 空元组(())
- 空字典({})
- 空字符串('')
- 零值(0)
- 特殊对象None
- 对象False(很明显)
提示:你也可以在自定义的对象里定义他们的布尔值属性(这个是python的高级用法)。
除以上几点以外的所有东西都视为``True``
{%if%}标签接受and,or或者not关键字来对多个变量做判断,或者对变量取反(not),例如:例如:
{%ifathlete_listandcoach_list%}
Bothathletesandcoachesareavailable.
{%endif%}
{%ifnotathlete_list%}
Therearenoathletes.
{%endif%}
{%ifathlete_listorcoach_list%}
Therearesomeathletesorsomecoaches.
{%endif%}
{%ifnotathlete_listorcoach_list%}
Therearenoathletesortherearesomecoaches.
{%endif%}
{%ifathlete_listandnotcoach_list%}
Therearesomeathletesandabsolutelynocoaches.
{%endif%}
{%if%}标签不允许在同一个标签中同时使用and和or,因为逻辑上可能模糊的,例如,如下示例是错误的:比如这样的代码是不合法的:
{%ifathlete_listandcoach_listorcheerleader_list%}
系统不支持用圆括号来组合比较操作。如果你确实需要用到圆括号来组合表达你的逻辑式,考虑将它移到模板之外处理,然后以模板变量的形式传入结果吧。或者,仅仅用嵌套的{%if%}标签替换吧,就像这样:
{%ifathlete_list%}
{%ifcoach_listorcheerleader_list%}
Wehaveathletes,andeithercoachesorcheerleaders!
{%endif%}
{%endif%}
多次使用同一个逻辑操作符是没有问题的,但是我们不能把不同的操作符组合起来。例如,这是合法的:
{%ifathlete_listorcoach_listorparent_listorteacher_list%}
并没有{%elif%}标签,请使用嵌套的``{%if%}``标签来达成同样的效果:
{%ifathlete_list%}
<p>Herearetheathletes:{{athlete_list}}.</p>
{%else%}
<p>Noathletesareavailable.</p>
{%ifcoach_list%}
<p>Herearethecoaches:{{coach_list}}.</p>
{%endif%}
{%endif%}
一定要用{%endif%}关闭每一个{%if%}标签。