使用迭代列表中的索引

Say*_*yse 0 python django list django-templates

我正在尝试根据当前在另一个列表上迭代的索引显示来自不同列表的值,但无法弄清楚如何访问各个项目..

{% for row in myarray.all %}
    <tr>
    <th>{{ my_other_array_where_I_cant_access_elements.forloop.counter }}</th>
    <td>{{ row }}</td>
    </tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我尝试使用,forloop.counter但这并没有显示任何内容,它只是创建了一个空的表头元素。

我的另一个数组在视图中定义如下,如果我删除forloop.counter然后我可以看到整个数组打印到表头

 my_other_array_where_I_cant_access_elements = ["X", "Y", "Z", "XX", "YY"]
Run Code Online (Sandbox Code Playgroud)

如果我遗漏了任何必需的详细信息,请告诉我。

ale*_*cxe 5

听起来您想同时迭代两个列表,即zip()列表。

如果是这种情况,最好在视图中执行此操作并在上下文中传递:

headers = ["X", "Y", "Z", "XX", "YY"]
data = zip(headers, myarray.all())
return render(request, 'template.html', {'data': data})
Run Code Online (Sandbox Code Playgroud)

然后,在模板中:

{% for header, row in data %}
    <tr>
        <th>{{ header }}</th>
        <td>{{ row }}</td>
    </tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)