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

 

posted on 2016-10-30 23:49  小作一个  阅读(8357)  评论(0编辑  收藏  举报

导航