python - 在 django 模板中使用循环,就像在 python 中使用它们一样

标签 python django django-templates django-views

我可以在 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.counter0forloop.counter。 (从 0 开始,从 1 开始)。请参阅for template tag .

顺便说一句,代码不需要索引,因为代码只打印列表的元素。

关于python - 在 django 模板中使用循环,就像在 python 中使用它们一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20702784/

相关文章:

python - Django 模板中的后向关系

django - 如何获取模板中当前应用程序的名称?

python - 用 Python 编写游戏循环的正确方法是什么?

python - 列表理解的扩展导致列表幂集中的无限循环

django - 数以千计的外来 unicorn worker

python - 如何从django信号返回数据?

python - 如何重新导入 jupyter html 文件?

python - "*"在 Python 中是什么意思?

Django 序列化程序不存在 'geojson' ?

django - 如何在 Django 项目/应用程序中组织和加载 CSS?