在Django模板循环中使用列表索引查找

3 投票
2 回答
2725 浏览
提问于 2025-04-17 02:03

基本上,我想做的是让模板系统遍历两个独立的列表,以填充一个表格的两列。我的想法是使用一个索引列表(numList)来访问这两个列表的相同索引。我尝试在模板循环中使用点符号来查找列表的索引,但在循环中似乎不起作用。有没有什么办法可以解决这个问题?

numList = [0, 1, 2, 3]
placeList = ['park', 'store', 'home', 'school']
speakerList = ['bill', 'john', 'jake', 'tony']

        <table>
            <tr>
                <th>Location</th>
                <th>Time</th>
                <th>Speaker</th>
            </tr>
            {% for num in numList %}
             <tr>
                <td>{{ placeList.num }}</td>
                <td>1:30</td>
                <td>{{ speakerList.num }}</td>
             </tr>
             {% endfor %}
        </table>

2 个回答

0

你可以把这两个列表合并成一个。

比如说:

yourlist = [('park','bill'),('store','john'),('home','jake'),...]
5

最简单的方法可能就是先把你的列表在Python中合并,然后在模板里查看这个合并后的列表:

combinedList = [(placeList[i],speakerList[i]) for i in range(4)]

{% for entry in combinedList %}
<tr>
<td>{{ entry.0 }}</td>
<td>1:30</td>
<td>{{ entry.1 }}</td>
</tr>
{% endfor %}

或者为了更清楚明了,你可以把合并后的列表做成一个对象列表或者字典列表,比如这样:

combinedList = [{'place':placeList[i],'speaker':speakerList[i]} for i in range(4)]

{% for entry in combinedList %}
<tr>
<td>{{ entry.place }}</td>
<td>1:30</td>
<td>{{ entry.speaker }}</td>
</tr>
{% endfor %}

撰写回答