Enumerating Through Lists in a Django Template

greenteabiscuit

Reishi Mitani

Posted on August 3, 2020

Enumerating Through Lists in a Django Template

Environment

python 3.6.5
django 2.1

===============

Enumerating in a Django Template

I recently had a problem where I had to enumerate through a list passed from the view to the template. You can use these methods below.

variable definition
forloop.counter enumerating, index starting from 1
forloop.counter0 enumerating, index starting from 0
forloop.revcounter enumerating, index starting from the tail
forloop.revcounter0 enumerating, index starting from 0
forloop.first true when index is at 0
forloop.last true when index is at tail
forloop.parentloop enumerates through the parent loop

An example of the forloop.counter will be:

{% for person in listlike_var %}
    {{ forloop.counter }} : {{ person.name }}
{% endfor %}
Enter fullscreen mode Exit fullscreen mode

Output:

1: sally
2: bob
3: john
Enter fullscreen mode Exit fullscreen mode

For forloop.counter0 it will be:

{% for person in listlike_var %}
    {{ forloop.counter0 }} : {{ person.name }}
{% endfor %}
Enter fullscreen mode Exit fullscreen mode
0: sally
1: bob
2: john
Enter fullscreen mode Exit fullscreen mode

As for the length of a list, listlike_var|length can be used.

{{ listlike_var|length }}
Enter fullscreen mode Exit fullscreen mode
3
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
greenteabiscuit
Reishi Mitani

Posted on August 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related