Python 在 Django 模板中按索引引用列表项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4651172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reference list item by index within Django template?
提问by user456584
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?
这可能很简单,但我环顾四周,找不到答案。从 Django 模板引用列表中单个项目的最佳方法是什么?
In other words how do I do the equivalent of {{ data[0] }}within the template language?
换句话说,我如何{{ data[0] }}在模板语言中做等效的事情?
Thanks.
谢谢。
采纳答案by Mike DeSimone
It looks like {{ data.0 }}. See Variables and lookups.
看起来像{{ data.0 }}。请参阅变量和查找。
回答by yilmazhuseyin
{{ data.0 }}should work.
{{ data.0 }}应该管用。
Let's say you wrote data.objdjango tries data.objand 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.
假设您编写了data.objdjango 尝试data.obj和data.obj(). 如果它们不起作用,它会尝试data["obj"]。在你的情况下data[0]可以写成{{ data.0 }}. 但我建议您拉data[0]入视图并将其作为单独的变量发送。
回答by WeizhongTu
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
更好的方法:自定义模板过滤器:https: //docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
例如在模板中获取 my_list[x]:
in template
在模板中
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
模板标签/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]
如果my_list = [['a','b','c'], ['d','e','f']],你可以{{ my_list|index:x|index:y }}在模板中使用得到my_list[x][y]
It works fine with "for"
它适用于“for”
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
经过测试,效果很好^_^
回答by Kendrick Fong
@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.
@jennifer06262016,您绝对可以添加另一个过滤器来返回 django 查询集中的对象。
@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.
在这种情况下,您可以在模板中输入类似 {{ Queryset|index:x|get_item }} 的内容来访问某个字典对象。这个对我有用。

