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?

Asked By: user456584

||

Answers:

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

Answered By: Mike DeSimone

{{ 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.

Answered By: yilmazhuseyin

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 ^_^

Answered By: WeizhongTu

@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.

Answered By: Kendrick Fong

first make sure that the app contain custom tag function is added to INSTALLED APP follow the instruction below

1 in the main directory app create another directory with name templatetags at the same level as model.py,views.py,urls.py.

2 inside of templatetags directory create init.py and another file with the name of your custom tags, for example: my_tags.py.

MainApp/
    __init__.py
    models.py
    templatetags/
        __init__.py
        my_tags.py
    views.py

in your template you would use the following:

{% load my_tags.py %}

in my_tags.py:

from django import template 
register = template.Library()
@register.filter(name="get")
def get(indexable, i):
    return indexable[i]

in views.py:

number = [0,1,2,3,4,5]

return render(
    "index.html", {"number":number}

)

in index.html:

{% load my_tags %}

{{numer|get:forloop.counter0}}

reference How to create custom template tags and filters

i hope you understand, because ingles not my native language

Answered By: Mario Mutondo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.