我可以在 django 模板中做这样的事情吗?:
firstList = ["foo", "bar"]
secondList = ["foo", "bar"]
for counter_one, _firstList in enumerate(firstList):
for counter_two, _secondList in enumerate(secondList):
if firstList[counter_one] == secondList[counter_two]:
print(firstList[counter_one])
因为如果我能的话那就太棒了:D
最佳答案
>>> from django.template import Template, Context
>>> t = Template('''
... {% for first in firstList %}
... {% for second in firstList %}
... {% if first == second %}
... {{ first }}
... {% endif %}
... {% endfor %}
... {% endfor %}
... ''')
>>> t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']}))
u'\n \n \n \n foo\n \n \n \n \n \n \n \n \n \n bar\n \n \n \n'
>>> print(t.render(Context({'firstList': ['foo', 'bar'], 'secondList': ['foo', 'bar']})))
foo
bar
如果您需要内循环的索引,请使用fooloop.counter0
或forloop.counter
。 (从 0 开始,从 1 开始)。请参阅for
template tag .
顺便说一句,代码不需要索引,因为代码只打印列表的元素。
关于python - 在 django 模板中使用循环,就像在 python 中使用它们一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20702784/