Django template for 循環用法


當列表為空或者非空時執行不同操作:

{% 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 %}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM