use*_*584 91 python django django-templates
这可能很简单,但我环顾四周,找不到答案.从Django模板引用列表中的单个项目的最佳方法是什么?
换句话说,我如何{{ data[0] }}在模板语言中做相同的操作?
谢谢.
Wei*_*gTu 65
更好的方法:自定义模板过滤器:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
例如在模板中获取List [x]:
在模板中
{% load index %}
{{ my_list|index:x }}
Run Code Online (Sandbox Code Playgroud)
templatetags/index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
Run Code Online (Sandbox Code Playgroud)
如果my_list = [['a','b','c'], ['d','e','f']],你可以{{ my_list|index:x|index:y }}在模板中使用my_list[x][y]
它适用于"for"
{{ my_list|index:forloop.counter0 }}
Run Code Online (Sandbox Code Playgroud)
测试并且运行良好^ _ ^
yil*_*yin 22
{{ data.0 }} 应该管用.
假设你写了data.objdjango尝试data.obj和data.obj().如果他们不工作,它会尝试data["obj"].在你的情况下data[0]可以写成{{ data.0 }}.但我建议你拉data[0]入视图并将其作为单独的变量发送.