【问题标题】:using list index lookup within a template loop in django在 django 的模板循环中使用列表索引查找
【发布时间】:2011-09-11 20:37:32
【问题描述】:

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


    【解决方案1】:

    最简单的可能是在 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 %}
    

    或者为了透明,您可以将 combineList 设为对象或字典的列表,例如:

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

    【讨论】:

    • combinedList = zip(placeList, speakerList) 更好
    【解决方案2】:

    您可以将这两个列表合二为一。

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-06
      • 2015-11-05
      • 2020-12-02
      • 2015-05-25
      • 2021-10-18
      • 2011-01-30
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多