Python Django模板:迭代列表

Tim*_*ung 11 python django django-templates

从技术上讲,它应该从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 %}
Run Code Online (Sandbox Code Playgroud)

这当前没有输出:(如果我用0 ... {{c.0.0.from_user}}替换"i"...它将输出一些东西..(第一个用户10次)

Chr*_*ble 20

你需要i成为一个指数吗?如果没有,请查看以下代码是否符合您的要求:

<div id="right_pod">
{% for i in c %}
    <div class="user_pod">
        {{ i.0.from_user }}
    </div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • -1表示*必须*执行此操作是控制器.假设您需要页面其他部分的完整列表.传递完整列表*和*截断列表是浪费的.在这种情况下,您应该只传递完整列表并使用@sotangochips建议的切片过滤器. (2认同)

iro*_*ggy 14

请阅读模板语言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)
Run Code Online (Sandbox Code Playgroud)


sot*_*ips 8

您应该使用切片模板过滤器来实现您想要的效果:

迭代对象(在本例中为c),如下所示:

{% for c in objects|slice:":30" %}
Run Code Online (Sandbox Code Playgroud)

这将确保您只迭代前30个对象.

此外,您可以使用forloop.counter对象来跟踪您正在进行的循环迭代.