【问题标题】:Python Django Template: Iterate Through ListPython Django 模板:遍历列表
【发布时间】:2010-10-21 12:17:20
【问题描述】:

从技术上讲,它应该从 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 %}

这目前什么都不输出:(如果我用 0...{{c.0.0.from_user}} 替换“i”...它将输出一些东西..(第一个用户 10 次)

【问题讨论】:

  • 请提供c的结构。否则这很难解释。

标签: python django django-templates


【解决方案1】:

您需要i 作为索引吗?如果没有,请查看以下代码是否符合您的要求:

<div id="right_pod">
{% for i in c %}
    <div class="user_pod">
        {{ i.0.from_user }}
    </div>
{% endfor %}

【讨论】:

  • 理想情况下,我需要 i 成为一个索引,这样我就可以限制循环访问的用户数量。在将 c 传递给模板之前,我应该在 Controller 中执行此操作吗?
  • +1 用于在控制器层执行此操作;视图不应该包含这样的业务逻辑。
  • -1 表示 必须 这样做是控制器。假设您需要页面其他部分的完整列表。传入完整列表截断列表是很浪费的。在这种情况下,您应该只传递完整列表并使用@sotangochips 建议的切片过滤器。
【解决方案2】:

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

像这样遍历对象(在本例中为 c):

{% for c in objects|slice:":30" %}

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

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

【讨论】:

    【解决方案3】:

    请阅读完整的documentation on the template language's for loops。首先,迭代(就像在 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)
    

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 2013-06-22
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2011-01-25
      • 2013-04-08
      相关资源
      最近更新 更多