【问题标题】:Django - get element index in a list in template [duplicate]Django - 获取模板列表中的元素索引[重复]
【发布时间】:2017-10-25 14:29:03
【问题描述】:

我在模板中有一个用于迭代的列表,在迭代时,我想在这个列表中打印它的索引。现在我使用list.index(element),但这不起作用。

我愿意:

<tbody>
   {% for core in cores %}
   <tr>
       <td>{{cores.index(core)}}</td>     <!-- this line doesn't work -->
       <td>{{core.user}}</td>             <!-- this line works. -->

这不是办法吗?我必须做for i in length(cores)

【问题讨论】:

  • 最快的,正是我想要的……给它作为答案,我接受它。
  • 链接的标题不好......我建议将其标记为这个问题的重复或编辑......我事先搜索过,虽然答案很有价值,但显然标题具有误导性......跨度>

标签: python django django-templates


【解决方案1】:

{{forloop.counter}} 就是这样。 只在元素前添加这一行

【讨论】:

  • 是的,我在第一条评论中看到了...但是我认为 counter 和 counter0 都应该被提及...谢谢。
猜你喜欢
  • 2018-08-06
  • 1970-01-01
  • 2021-03-10
  • 2022-08-17
  • 1970-01-01
  • 2013-12-03
  • 2018-07-06
  • 2018-07-01
  • 2020-10-31
相关资源
最近更新 更多