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