python template用法_Django中template for如何使用方法

3a2c5c47719654b2eb3ed26ac95e70d8.png

之前我们讲过很多次for循环了,python中的循环有不少,不知道有没有听过template for这个循环,这个也算是for循环的这一种延伸。

在for循环中还有很多有用的东西,如下:

变量

描述

forloop.counter

索引从 1 开始算

forloop.counter0

索引从 0 开始算

forloop.revcounter

索引从最大长度到 1

forloop.revcounter0

索引从最大长度到 0

forloop.first

当遍历的元素为第一项时为真

forloop.last

当遍历的元素为最后一项时为真

forloop.parentloop

用在嵌套的 for 循环中,

获取上一层 for 循环的 forloop

也许有的小伙伴对template for的用法不是很明确,借着这个机会,今天来讲讲新朋友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 %}

到此这篇关于Django中template for如何使用方法的文章就介绍到这了,更多相关Django template for内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django的for循环标签用于在模板迭代列表、字典和查询集等可迭代对象,并在循环体输出每个元素的值。 以下是Django常用的for循环标签: 1. for...in:迭代列表、元组、集合等序列类型。 ```html {% for item in items %} {{ item }} {% endfor %} ``` 2. for...in...empty:迭代列表、元组、集合等序列类型,同时处理空序列的情况。 ```html {% for item in items %} {{ item }} {% empty %} 暂无数据 {% endfor %} ``` 3. for...in...reversed:倒序迭代列表、元组、集合等序列类型。 ```html {% for item in items reversed %} {{ item }} {% endfor %} ``` 4. for...in...if:迭代列表、元组、集合等序列类型,并根据条件过滤元素。 ```html {% for item in items %} {% if item > 5 %} {{ item }} {% endif %} {% endfor %} ``` 5. for...in...if...else:迭代列表、元组、集合等序列类型,并根据条件过滤元素,同时处理条件不成立的情况。 ```html {% for item in items %} {% if item > 5 %} {{ item }} {% else %} 不符合条件 {% endif %} {% endfor %} ``` 6. for...in...else:迭代列表、元组、集合等序列类型,同时处理空序列和非空序列的情况。 ```html {% for item in items %} {{ item }} {% empty %} 暂无数据 {% endfor %} ``` 7. for...in...counter:迭代列表、元组、集合等序列类型,并输出当前迭代的次数。 ```html {% for item in items %} {{ forloop.counter }}. {{ item }} {% endfor %} ``` 8. for...in...counter0:迭代列表、元组、集合等序列类型,并输出当前迭代的次数(从0开始)。 ```html {% for item in items %} {{ forloop.counter0 }}. {{ item }} {% endfor %} ``` 9. for...in...cycle:迭代列表、元组、集合等序列类型,并轮流输出指定的多个值。 ```html {% for item in items %} {{ item }}{% cycle 'red' 'green' 'blue' %} {% endfor %} ``` 以上为Django常用的for循环标签,可以根据实际需求选择使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值