Fix Python – How to output loop.counter in python jinja template?

Question

Asked By – Rolando

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

According to the docs, there is a loop.counter variable that I am trying to use:

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

But is being outputed to my template. What is the correct syntax?

Now we will see solution for issue: How to output loop.counter in python jinja template?


Answer

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

In addition to loop.index, there is also

This question is answered By – sigi

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0