python - 在 django 的模板循环中使用列表索引查找

标签 python django list django-templates

基本上,我想要做的是让模板系统循环通过两个独立的列表来填充表格的两列。我的方法是使用索引列表 (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>

最佳答案

最简单的事情可能是在 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 设为对象或字典的列表,例如:

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 %}

关于python - 在 django 的模板循环中使用列表索引查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7381081/

相关文章:

c++ - 如何在 C++ 类中使用列表

python - 来自 Python 的 7zip 命令

python - 仅使用传递的参数子集创建 namedtuple 对象

python - 在直方图中记录计数值,而不是轴本身

python - 立即打印 Celery for Python 中已编程任务的任务 ID

reactjs - 无法读取不可变记录中的列表条目

c++ - 使用 C++ ifsteam 从文件读取到模板 vector

python - 当尝试编辑在 django 中创建的新配置文件时

python - Django 模型字段 : Checking "if field is not None" vs. "if field"

python - UPDATE不使用模型保存方法