如何访问Django模板中的数组元素? [英] How to access array elements in a Django template?
问题描述
我将一个数组 arr
传递给我的Django模板。我想访问数组中的数组的各个元素,例如 arr [0]
, arr [1]
etc而不是遍历整个数组。
I am getting an array arr
passed to my Django template. I want to access individual elements of the array in the array e.g. arr[0]
, arr[1]
etc instead of looping through the whole array.
有没有办法在Django模板中执行此操作?
Is there a way to do that in a Django template?
谢谢。
推荐答案
记住Django模板中的点符号用于Python中的四种不同的符号。在模板中, foo.bar
可以表示任何一种:
Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar
can mean any of:
foo[bar] # dictionary lookup
foo.bar # attribute lookup
foo.bar() # method call
foo[bar] # list-index lookup
它按此顺序尝试它们,直到找到匹配项。所以 foo.3
将会得到你的列表索引,因为你的对象不是一个以3为键的dict,没有一个名为3的属性,有一个名为3的方法。
It tries them in this order until it finds a match. So foo.3
will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.
这篇关于如何访问Django模板中的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!