How to output loop.counter in python jinja template?

Rolando picture Rolando · Aug 27, 2012 · Viewed 156.8k times · Source

I want to be able to output the current loop iteration to my template.

According to the docs: http://wsgiarea.pocoo.org/jinja/docs/loops.html, there is a loop.counter variable that I am trying to use.

I have the following:

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

Though nothing is being output to my template. What is the correct syntax?

Answer

sigi picture sigi · Aug 27, 2012

The counter variable inside the loop is called loop.index in 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

See http://jinja.pocoo.org/docs/templates/ for more.