【问题标题】:Django - Use forloop.counter0Django - 使用 forloop.counter0
【发布时间】:2016-10-14 21:29:47
【问题描述】:

我想在模板 html 上的列表中显示元素:

<table class="table table-striped col-md-12">
    <tbody>
        {% for row in list %}
        <tr>
            <td>{{ row.0 }}</td>
            <td>{{ row.1 }}</td>
            <td>{{ ..... }}</td>
        </tr>
        {% endfor %}
    </tbody>

len(list) 演变时,我需要手动调用新行。 因此,要进行通用调用并取决于列表中的长度,我选择了方法forloop.counter0,但是当我编写代码时,我的屏幕上出现错误或没有元素。

<tr>
  {% for i in "xxx" %}
      <td>{{ row.forloop.counter0 }}</td>
  {% endfor %}
</tr>

【问题讨论】:

  • 什么是list?这听起来更像是你需要一个对象模型而不是随机索引
  • 因为在我看来,我读取 csv 并获取列表中的元素:list_test = [] for row in reader: list_test.append((row))
  • row 变量是否有 forloop 成员?另外,我真的不确定您要做什么。还有一个{% endfor %} 额外...
  • 只是我想通过第二个 div 切换(第一个 div)循环上的元素,然后这样做:{for } div2 {end for}
  • 我将显示我列表中的所有元素,此列表不是静态的,在此列表中您可以有 1 行或很多行,我想用 forloop 显示此行以添加新行,不要手动写 row.0,row.1,...。

标签: python django python-3.x django-1.9


【解决方案1】:

您根本不需要查找索引,只需在里面有另一个 forloop 循环遍历行

{% for i in row %}
   <td>{{ i }}</td>
{% endfor %}

如果您需要更精细的数据,您可能需要考虑制作一个实际模型来表示数据,然后遍历该模型的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2018-12-03
    • 2016-05-26
    • 2015-06-30
    • 2014-11-03
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多