Django template for 循環用法

當列表爲空或者非空時執行不一樣操做:oop

{% for item in list %}
    ...
{% empty %}
    ...
{% endfor %}

 

使用forloop.counter訪問循環的次數,下面這段代碼依次輸出循環的次數,從1開始計數:spa

{% for item in list %}
    ...
    {{ forloop.counter }}
    ...
{% endfor %}

 

從0開始計數:code

{% for item in list %}
    ...
    {{ forloop.counter0 }}
    ...
{% endfor %}

 

判斷是不是第一次循環:blog

{% for item in list %}
    ...
    {% if forloop.first %}
        This is the first round. 
    {% endif %}
    ...
{% endfor %}

 

判斷是不是最後一次循環:it

{% for item in list %}
    ...
    {% if forloop.last %}
        This is the last round.
    {% endif %}
    ...
{% endfor %}

 

逆向循環:ast

{% for item in list reversed %}
    {{ item }}
{% endfor %}
相關文章
相關標籤/搜索