Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current index of for loop with jijna2?

Tags:

python

jinja2

Let's say that I have a code like:

{% for x in posts %}
   <p>We are in item: {{ x }}</>
{% else %}

And I want to get the current index of the for loop to run an if loop, something like(logically):

{% for x in posts %}
 {% if x.index = 0 %}
   <p>We are in the first item!</p>
 {% else %}
   <p>We are in item: {{ x }}</>
 {% endif %}
{% endfor %}

How to do it inside jijna2? (I use Python with Flask).

like image 682
Madno Avatar asked Jun 27 '15 09:06

Madno


Video Answer


1 Answers

You can use loop.index inside the loop.

{% for x in posts %}
    <p>We are in item number: {{ loop.index }}</>
{% else %}

Flask Template docs

like image 65
ssundarraj Avatar answered Nov 05 '22 10:11

ssundarraj