标签 eif/else
{% if %} 标签检查(evaluate)一个变量,如果这个变量为真(即,变量存在,非空,不是布尔值假),系统会显示在 {% if %} 和 {% endif %} 之间的任何内容,例如:
1 {% if today_is_weekend %}
2 Welcome to the weekend!
3 {% endif %}
{% else %} 标签是可选的:
1 {% if today_is_weekend %}
2 Welcome to the weekend!
3 {% else %}
4 Get back to work.
5 {% endif %}
Python 的“真值”
在Python和Django模板系统中,以下这些对象相当于布尔值的False:
空列表([] )
空元组(() )
空字典({} )
空字符串('' )
零值(0 )
特殊对象None
对象False(很明显)
除以上几点以外的所有东西都视为"True"。
{% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反( not ),例如:
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
{% if %} 标签不允许在同一个标签中同时使用 and 和 or ,因为逻辑上可能模糊的,例如,如下示例是错误的: 比如这样的代码是不合法的:
{% if athlete_list and coach_list or cheerleader_list %}
系统不支持用圆括号来组合比较操作。 如果你确实需要用到圆括号来组合表达你的逻辑式,考虑将它移到模板之外处理,然后以模板变量的形式传入结果吧。 或者,仅仅用嵌套的{% if %}标签替换吧,就像这样:
1 {% if athlete_list %}
2 {% if coach_list or cheerleader_list %}
3 We have athletes, and either coaches or cheerleaders!
4 {% endif %}
5 {% endif %}
多次使用同一个逻辑操作符是没有问题的,但是我们不能把不同的操作符组合起来。 例如,这是合法的:
{% if athlete_list or coach_list or parent_list or teacher_list %}
并没有 {% elif %} 标签, 请使用嵌套的`` {% if %}`` 标签来达成同样的效果:
1 {% if athlete_list %}
2 Here are the athletes: {{ athlete_list }}.
3 {% else %}
4 No athletes are available.
5 {% if coach_list %}
6 Here are the coaches: {{ coach_list }}.
7 {% endif %}
8 {% endif %}
PS:一定要用 {% endif %} 关闭每一个 {% if %} 标签。
for
{% for %} 允许我们在一个序列上迭代。 与Python的 for 语句的情形类似,循环语法是 for X in Y ,Y是要迭代的序列而X是在每一个特定的循环中使用的变量名称。 每一次循环中,模板系统会渲染在 {% for %} 和{% endfor %} 之间的所有内容。
例如,给定一个运动员列表 athlete_list 变量,我们可以使用下面的代码来显示这个列表:
1
2 {% for athlete in athlete_list %}
3 {{ athlete.name }}
4 {% endfor %}
5
给标签增加一个 reversed 使得该列表被反向迭代:
{% for athlete in athlete_list reversed %} ... {% endfor %}
可以嵌套使用 {% for %} 标签:
1 {% for athlete in athlete_list %}
2 {{ athlete.name }}
3
4 {% for sport in athlete.sports_played %}
5 {{ sport }}
6 {% endfor %}
7
8 {% endfor %}
在执行循环之前先检测列表的大小是一个通常的做法,当列表为空时输出一些特别的提示。
1 {% if athlete_list %}
2 {% for athlete in athlete_list %}
3 {{ athlete.name }}
4 {% endfor %}
5 {% else %}
6 There are no athletes. Only computer programmers.
7 {% endif %}
1 {% for country in countries %}
2
3 {% for city in country.city_list %}
4
5 Country #{{ forloop.parentloop.counter }}
6 City #{{ forloop.counter }}
7 {{ city }}
8
9 {% endfor %}
10
11 {% endfor %}