Python Django 模板:遍历列表
从技术上讲,这段代码应该从0开始循环到rangeLength,然后输出c[i][0].from_user的用户名……但是我在网上看到的例子似乎把方括号换成了点号的写法。我有以下代码:
<div id="right_pod">
{%for i in rangeLength%}
<div class="user_pod" >
{{c.i.0.from_user}}
</div>
{% endfor %}
现在这段代码什么都不输出 :( 如果我把“i”换成0……{{c.0.0.from_user}}……它就会输出一些东西……(第一个用户输出10次)
3 个回答
9
你可以使用切片模板过滤器来实现你想要的效果:
像这样遍历这个对象(在这个例子中是c):
{% for c in objects|slice:":30" %}
这样做可以确保你只遍历前30个对象。
另外,你还可以使用forloop.counter对象来跟踪你当前是第几次循环。
15
请先阅读整个关于模板语言中for循环的文档。首先,这里的循环(就像在Python中一样)是针对对象的,而不是索引。其次,在任何for循环中都有一个forloop变量,其中有两个你可能会感兴趣的字段:
Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
28
你需要 i
作为一个索引吗?如果不需要,可以看看下面的代码是否能满足你的需求:
<div id="right_pod">
{% for i in c %}
<div class="user_pod">
{{ i.0.from_user }}
</div>
{% endfor %}