Как вывести loop.counter в шаблоне python jinja?

111

Я хочу иметь возможность выводить текущую итерацию цикла на мой шаблон.

Согласно документам: 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>

Хотя ничто не выводится на мой шаблон. Каков правильный синтаксис?

  • 0
    У вас есть {% for user in userlist %} дважды. Я предполагаю, что это не правильно.
Теги:
jinja2

3 ответа

236
Лучший ответ

Переменная счетчика внутри цикла называется loop.index в jinja2.

>>> from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

Подробнее см. http://jinja.pocoo.org/docs/templates/.

  • 112
    Стоит отметить, что если вам нужен индекс на основе 0, вы можете использовать loop.index0 .
  • 0
    Что удивительно, так это то, что ссылки на это я не смог найти на их веб-сайте, в то время как counter и counter0 задокументированы, но отсутствуют в версии, которую я установил вчера.
Показать ещё 1 комментарий
17

Внутри блока for-loop вы можете получить доступ к некоторым специальным переменным, включая loop.index --but no loop.counter. Из официальных документов:

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).
0

если вы используете 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>
  • 0
    Да! Отлично, у меня сработало в Django .

Ещё вопросы

Сообщество Overcoder
Наверх
Меню