Reference list item by index within Django template?


Question

This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?

In other words how do I do the equivalent of {{ data[0] }} within the template language?

Thanks.

1
87
1/10/2011 8:27:43 PM

Accepted Answer

It looks like {{ data.0 }}. See Variables and lookups.

152
12/19/2018 9:31:10 PM

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get List[x] in templates:

in template

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

templatetags/index.py

from django import template
register = template.Library()

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

if List = [['a','b','c'], ['d','e','f']], you can use {{ List|index:x|index:y }} in template to get List[x][y]

It works fine with "for"

{{ List|index:forloop.counter0 }}

Tested and works well ^_^


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon