Reference list item by index within Django template?

PythonDjangoDjango Templates

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

such as get my_list[x] in templates:

in template

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

templatetags/index.py

from django import template
register = template.Library()

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

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

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

Solution 3 - Python

{{ data.0 }} should work.

Let's say you wrote data.obj django tries data.obj and data.obj(). If they don't work it tries data["obj"]. In your case data[0] can be written as {{ data.0 }}. But I recommend you to pull data[0] in the view and send it as separate variable.

Solution 4 - Python

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser456584View Question on Stackoverflow
Solution 1 - PythonMike DeSimoneView Answer on Stackoverflow
Solution 2 - PythonWeizhongTuView Answer on Stackoverflow
Solution 3 - PythonyilmazhuseyinView Answer on Stackoverflow
Solution 4 - PythonKendrick FongView Answer on Stackoverflow