在Django模板中按索引引用列表项?

问题:在Django模板中按索引引用列表项?

这可能很简单,但是我环顾四周,找不到答案。从Django模板引用列表中的单个项目的最佳方法是什么?

换句话说,{{ data[0] }}在模板语言中我该如何做?

谢谢。

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.


回答 0

看起来像{{ data.0 }}。请参阅变量和查找

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


回答 1

更好的方法:自定义模板过滤器:https : //docs.djangoproject.com/en/dev/howto/custom-template-tags/

例如在模板中获取my_list [x]:

在模板中

{% 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]

如果my_list = [['a','b','c'], ['d','e','f']],您可以{{ my_list|index:x|index:y }}在模板中使用my_list[x][y]

与“ for”一起正常工作

{{ my_list|index:forloop.counter0 }}

经过测试,效果很好^ _ ^

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


回答 2

{{ data.0 }} 应该管用。

假设您写了data.objdjango try data.objdata.obj()。如果他们不起作用,它会尝试data["obj"]。你的情况data[0]可以写成{{ data.0 }}。但是我建议您data[0]插入视图并将其作为单独的变量发送。

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


回答 3

@ jennifer06262016,您绝对可以添加另一个过滤器以返回Django Queryset中的对象。

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

在这种情况下,您可以在模板中输入类似{{Queryset | index:x | get_item}}的内容,以访问某些字典对象。这个对我有用。

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