在我的 Django/Python 应用程序中,我将多个可迭代对象从views.py 传递到index.html。 我本质上是在尝试制定一个标准的 for 循环,您可以在其中通过索引获取项目。一旦我迭代第一个对象,如何获取同一循环中另一个可迭代对象的相应索引?
条件:所有数组的长度始终相等,但它们的长度每天都会变化。
views.py
name = ['John', 'Kim', 'Tim', 'Jill']
age = ['20', '30', '52', '27']
state = ['IN', 'IL', 'CA', 'TX']
city = ['Muncie', 'Champaign', 'Fresno', 'Dallas']
def index(request):
args = {'names': name, 'ages': age, 'states': state, 'cities': city}
return render(request, 'index.html', args)
index.html
{% extends 'base.html' %}
{% load staticfiles %}
{% block Data %}
{% for name in names %}
<p>{{ name }}</p>
<p>{{ age.forloop.counter0 }}</p>
<p>{{ state.forloop.counter0 }}</p>
<p>{{ city.forloop.counter0 }}</p>
{% endfor %}
{% endblock %}
正如你所看到的,我想我会使用“forloop.counter0”作为我的索引。但它显然不是这样工作的。关于如何实现这一目标有什么建议吗? 提前致谢!
最佳答案
您可以压缩
View 中的列表并将其解压到模板中:
def index(request):
data = zip(name, age, state, city)
args = {'data': data}
return render(request, 'index.html', args)
然后在模板中:
{% for name, age, state, city in data %}
{{ name }}
{{ age }}
{{ state }}
{{ city }}
{% endfor %}
您还可以使用具有适当属性的对象或命名元组。
关于python - 如何获取可迭代对象中的第 i 个项目。 Django/Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352918/