3

Basically, what I want to do is have the template system loop through two independent lists to fill two columns of a table. My approach was to use an index list (numList) as a way to access the same index of the two lists. I tried using the dot notation for list index lookup within a template loop but it doesn't seem to work in the loop. Any ideas on how I can remedy this?

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 Answers 2

5

The easiest thing is probably to combine your lists in python and then just look through the combined list in the template:

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

Or for transparency, you could make combinedList a list of objects or dictionaries for example:

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

combinedList = zip(placeList, speakerList) is better
0

You could aggregate these two lists in one.

For example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.