在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屋!