我有一个列表['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
。
在我的django模板中,我希望输出为
a b
c d
e f
g h
这就是我正在做的事情: -
{% for i in list|slice:"::2" %}
{{i}} {{}} // how do I get the second element?
{% endfor %}
我错过了什么?
以下是python等价物: -
for i in range(0, len(list), 2):
print list[i], list[i+1]
答案 0 :(得分:3)
我不知道你的“第二元素”是什么意思。像这样列出一个列表会给你['a', 'c', 'e', 'g']
,而i
将依次为每个列表。
我怀疑你根本不想这样做;您可能希望遍历整个列表并使用{% if forloop.counter|divisibleby:2 %}
来确定何时插入新段落或中断标记。
答案 1 :(得分:1)
除了上一个答案。您也可以使用cycle tag。
{% for el in my_list %}
{{ el }}
{% cycle ' ' '<br>' %}
{% endfor %}
会给你想要的输出:
a b
c d
e f
g h