当列表为空或者非空时执行不同操作:

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2021-08-03
  • 2021-10-15
  • 2021-12-15
  • 2021-05-19
猜你喜欢
  • 2022-03-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-01
  • 2022-12-23
  • 2021-10-28
相关资源
相似解决方案