python - Django 嵌套 for 循环中的计数器

标签 python django django-templates

考虑

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
...
</li>
{% endfor %}
{% endfor %}
</ul>

在 Django 模板中,我应该用什么替换 ... 才能得到

1
2
3
4
5
6
7
8
9

即如何获得嵌套 for 循环的计数器,其中外部循环中元素的长度并不总是相同?

更新

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
  {{forloop.counter}}
</li>
{% endfor %}
{% endfor %}
</ul>

给出

1
2
3
1
2
1
2
3
4

<ul>
{% for l in [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] %}
{% for i in l %}
<li>
  {{forloop.parentloop.counter}}
</li>
{% endfor %}
{% endfor %}
</ul>

给出

1
1
1
2
2
3
3
3
3

最佳答案

对于内部循环,您可以使用{{ forloop.counter }}。同时,对于外循环,您可以使用 {{ forloop.parentloop.counter }}

更新

您是否尝试过执行{{ forloop.parentloop.counter|add:forloop.counter }}

Source

关于python - Django 嵌套 for 循环中的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823370/

相关文章:

python - Referer 检查失败(Referer 不安全,而主机安全)

django - 每个用户如何在 django 中的同一个表上获取增量和唯一 id

python 使用列表理解或其他方法将列表中的 None 替换为空白?也是嵌套列表解决方案

python - 使用 mysql-connector-python 从 mysql 中选择数据

django - Pydev + Django 工作流程。本地(测试)+远程同步。将 git 与 django 结合使用

python - Django静态图像不显示

django 模板更改行为为 Silent_variable_failure = False

python - 无法获取 Python/Tkinter 中单选按钮的值

java - 为什么我使用 java post-request 来响应状态代码 500 的内部服务器错误?

Django 多对多字段 : 'function' object is not subscriptable