Categories
Python Answers

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

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *