我有2个dicts的列表
foobar = [ {dict1},
{dict2}
]
Django的文档说切片模板标签与python切片完全相同。
所以我在python shell中测试过,果然:
>>> foo = [1,2]
>>> foo[-2]
1
但是,当我在模板中执行此操作时:
{% with foobar|slice:"-2" as previous_thing %}
{{ previous_thing }}
我得到一个空列表[]
。
{% with foobar|slice:"1" as previous_thing %}
产生我期望的结果(列表中的第一项),{{ foobar }}
(2个dicts的列表)也是如此。
到底是怎么回事?!
答案 0 :(得分:3)
>>> foo = [1,2]
这称为索引:
>>> foo[-2]
1
>>> foo[:-2] #return all items up to -2 index(i.e 0th index), so empty list
[]
>>> foo[:-1]
[1]
>>> foo[:2]
[1, 2]
切片也适用于不存在的索引:
>>> foo[-10000:100000]
[1, 2]
但索引不会:
>>> foo[100000]
Traceback (most recent call last):
foo[100000]
IndexError: list index out of range