Menu Close

How to reference list item by index within Python Django template?

To reference list item by index within Python Django template, we can create our own filter.

For instance, we write

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

to create the index filter by applying @register.filter decorator to the index function in templatetags/index.py.

Then in our templaye, we use it by writing

{% load index %}
{{ my_list|index:x }}

{{ my_list|index:forloop.counter0 }}

to use the index decorator after loading it by using the index as its argument

Posted in Python, Python Answers