之前我们讲过很多次for循环了,python中的循环有不少,不知道有没有听过template for这个循环,这个也算是for循环的这一种延伸。
也许有的小伙伴对template for的用法不是很明确,借着这个机会,今天来讲讲新朋友template for循环。
当列表为空或者非空时执行不同操作:
1 2 3 4 5 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list %}
...
{% empty %}
...
{% endfor %}<br></span></p>
|
使用forloop.counter访问循环的次数,下面这段代码依次输出循环的次数,从1开始计数:
1 2 3 4 5 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list %}
...
{{ forloop.counter }}
...
{% endfor %}<br></span></p>
|
从0开始计数:
1 2 3 4 5 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list %}
...
{{ forloop.counter0 }}
...
{% endfor %}<br></span></p>
|
判断是否是第一次循环:
1 2 3 4 5 6 7 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list %}
...
{% if forloop.first %}
This is the first round.
{% endif %}
...
{% endfor %}<br></span></p>
|
判断是否是最后一次循环:
1 2 3 4 5 6 7 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list %}
...
{% if forloop.last %}
This is the last round.
{% endif %}
...
{% endfor %}<br></span></p>
|
逆向循环:
1 2 3 | <p style= "line-height: 1.75em;" ><span style= "font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;" >{% for item in list reversed %}
{{ item }}
{% endfor %}<br></span></p>
|
以上就是Django中template for循环使用的使用方法,跟for循环相比较有什么不同呢?小伙伴们恶意找出来再跟小编进行交流。更多Python学习推荐:PyThon学习网教学中心。