Django if 标签
If 语句
if 语句对变量求值,如果值为 true,则执行一段代码。
实例
{% if greeting == 1 %}<h1>Hello</h1>{% endif %}
Elif
elif 关键字表示 "如果之前的条件不正确,则尝试此条件"。
实例
{% if greeting == 1 %}<h1>Hello</h1>{% elif greeting == 2 %}<h1>Welcome</h1>{% endif %}
Else
else 关键字捕获前面条件未捕获的任何内容。
实例
{% if greeting == 1 %}<h1>Hello</h1>{% elif greeting == 2 %}<h1>Welcome</h1>{% else %}<h1>Goodbye</h1>{% endif %}
运算符
上面的实例使用 == 运算符,该运算符用于检查变量是否等于某个值,但还有许多其他运算符可以使用,或者如果只想检查变量是否为空,甚至可以删除该运算符:
实例
{% if greeting %}<h1>Hello</h1>{% endif %}
==
等于
实例
{% if greeting == 1 %}<h1>Hello</h1>{% endif %}
!=
不等于
实例
{% if greeting != 1 %}<h1>Hello</h1>{% endif %}
<
小于
实例
{% if greeting < 3 %}<h1>Hello</h1>{% endif %}
<=
小于或等于
实例
{% if greeting <= 3 %}<h1>Hello</h1>{% endif %}
>
大于
实例
{% if greeting > 1 %}<h1>Hello</h1>{% endif %}
>=
大于或等于
实例
{% if greeting >= 1 %}<h1>Hello</h1>{% endif %}
and
检查多个条件是否为 true
实例
{% if greeting == 1 and day == "Friday" %}<h1>Hello Weekend!</h1>{% endif %}
or
检查其中一个条件是否为 true。
实例
{% if greeting == 1 or greeting == 5 %}<h1>Hello</h1>{% endif %}
and/or
and 与 or 组合
实例
{% if greeting == 1 and day == "Friday" or greeting == 5 %}
Django 中的 if 语句中不允许使用括号,因此在组合 and 和 or 运算符时,必须知道括号是为 and 而不是为 or 添加的。
也就是说,上面的例子编译器会这样读:
实例
{% if (greeting == 1 and day == "Friday") or greeting == 5 %}
is
检查两个对象的值是否相同。
实例
{% if x is y %}<h1>Hello</h1>{% endif %}
is not
检查两个对象的值是否不相同。
实例
{% if x is not y %}<h1>Hello</h1>{% endif %}
in
检查对象中是否存在特定项。
实例
{% if x in members %}<h1>Hello</h1>{% endif %}
not in
检查对象中是否不存在特定项。
实例
{% if x not in members %}<h1>Hello</h1>{% endif %}