在 Django 模板中动态获取列表项 [英] Get list item dynamically in django templates
问题描述
我在页面上有一些循环,需要取决于循环编号的列表项.
I have some loop on the page and need list item depending from loop number.
当我打电话时:
{{ mylist.1 }}
{{ mylist.2 }}
{{ mylist.3 }}
一切正常,但我真正需要的是:
all works fine but what I really need is something like:
{% for x in somenumber|MyCustomRangeTag %}
{{ mylist.x }}
{% endfor %}
MyCustomRangeTag 给了我 Python range()
它可以工作并且我已经将 x
作为数字.所以 x
是 1、2、3 等等,这取决于循环数.这可能吗?如何实现?
MyCustomRangeTag gives me Python range()
it works and I already have x
as number. So x
is 1, 2, 3 etc. depending from loop number.
Is this possible and how?
推荐答案
这是不可能直接的,因为 Django 认为 "x"
是在 mylist
中查找的关键- 而不是 x 的值.因此,当 x = 5
时,Django 会尝试查找 mylist["x"]
而不是 mylist[5]
.
This is not possible directly because Django thinks that "x"
is the key to lookup in mylist
- instead of the value of x. So, when x = 5
, Django tries to look up mylist["x"]
instead of mylist[5]
.
使用以下过滤器作为解决方法:
Use the following filter as workaround:
@register.filter
def lookup(d, key):
return d[key]
并像使用它一样
{{ mylist|lookup:x }}
这篇关于在 Django 模板中动态获取列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!