當列表為空或者非空時執行不同操作:
{% for item in list %}
...
{% empty %}
...
{% endfor %}
使用forloop.counter訪問循環的次數,下面這段代碼依次輸出循環的次數,從1開始計數:
{% for item in list %}
...
{{ forloop.counter }}
...
{% endfor %}
從0開始計數:
{% for item in list %}
...
{{ forloop.counter0 }}
...
{% endfor %}
判斷是否是第一次循環:
{% for item in list %}
...
{% if forloop.first %}
This is the first round.
{% endif %}
...
{% endfor %}
判斷是否是最后一次循環:
{% for item in list %}
...
{% if forloop.last %}
This is the last round.
{% endif %}
...
{% endfor %}
逆向循環:
{% for item in list reversed %}
{{ item }}
{% endfor %}
