DEV Community

Reishi Mitani
Reishi Mitani

Posted on

9 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (2)

Collapse
 
waylonwalker profile image
Waylon Walker

Interesting, I have never seen a Django template before. If there are nested loops is there a way to distinguish between inner and outer for loops. This magical for loop variable seems a bit mysterious to me. I have never really reached for a template language and mostly stuck with the built-in string Template for my very limited use of templates.

Collapse
 
greenteabiscuit profile image
Reishi Mitani

Sorry for the late reply.
For two loops, it seems like there is the forloop.parentloop .
e.g. forloop.parentloop.counter
However for three or more loops I do not know yet whether there is a way to distinguish each of them.

This stackoverflow might be of a help: stackoverflow.com/questions/237651...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay