ChatGPT解决这个技术问题 Extra ChatGPT

Reference list item by index within Django template?

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?


M
Mauricio Cortazar

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


The annoying thing is that I can't say {{ data.foo }}, where foo is a variable with an index value in it and not a property name.
If you're willing to create a custom tag, you can do a lot more. Here we're just working with the built-in stuff.
Link not working anymore, try this one : docs.djangoproject.com/en/1.10/ref/templates/api/…
B
Bakuutin

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


One of the simplest explanations to learn Template Tags' application!
This was great! But with the {{ List|index:x }} format, how do I access values where I would normally use a dot? {{ (List|index:x).name }} obviously does not work. Thank you!
Exactly what I was looking for. Thank you!
@SuperCode '0' means getting the index which starts from 0, not 1
also, as @JTFouquier asked, you can access element attributes using with as explained here
a
arulmr

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


K
Kendrick Fong

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