首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在python jinja模板中输出loop.counter?

如何在python jinja模板中输出loop.counter?
EN

Stack Overflow用户
提问于 2012-08-28 00:02:20
回答 5查看 202.4K关注 0票数 220

我希望能够将当前循环迭代输出到我的模板中。

根据文档:http://wsgiarea.pocoo.org/jinja/docs/loops.html,有一个我正在尝试使用的loop.counter变量。

我有以下几点:

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{loop.counter}}
  </li>
      {% if loop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

尽管没有输出到我的模板中。正确的语法是什么?

EN

回答 5

Stack Overflow用户

发布于 2014-07-25 23:24:06

在for-loop块中,您可以访问一些特殊的变量,包括loop.index,但不能访问loop.counter。来自the official docs

Variable    Description
loop.index  The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first  True if first iteration.
loop.last   True if last iteration.
loop.length The number of items in the sequence.
loop.cycle  A helper function to cycle between a list of sequences. See the explanation below.
loop.depth  Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem   The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem   The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)  True if previously called with a different value (or not called at all).
票数 54
EN

Stack Overflow用户

发布于 2019-01-10 10:52:37

如果您正在使用django,请使用forloop.counter而不是loop.counter

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{forloop.counter}}
  </li>
      {% if forloop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>
票数 24
EN

Stack Overflow用户

发布于 2020-11-30 18:51:30

将此{% if loop.counter == 1 %}更改为{% if forloop.counter == 1 %} {#your code here#} {%endfor%}

这是从{{ user }} {{loop.counter}}{{ user }} {{forloop.counter}}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12145434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档