NickP NickP - 1 month ago 5
Python Question

Accessing a List out of order in Jinja

I have setup the following list of lists being passed through to my Jinja template:


[(u'2nd Principle', 1, 1, 3, 33, 1, 100), (u'Test Principle', 1, 2, 6, 33, 1, 100)]


And thus far I am handling displaying this in a table as follows:

<tbody>
{% for p in performance %}
<tr>
{% for a in p %}<td>{{ a }}</td>{% endfor %}
</tr>
{% endfor %}
</tbody>


This works perfectly in printing out each of the lists as a row. However, I have been trying to work with the same list in a different view where I want to show one less item and in a different order.

However, the following does not seem to work for me:

<tbody>
{% for p in performance %}
<tr>
<td>{{ p[6] }}</td>
<td>{{ p[1] }}</td>
<td>{{ p[3] }}</td>
<td>{{ p[2] }}</td>
<td>{{ p[5] }}</td>
<td>{{ p[6] }}</td>
</tr>
{% endfor %}
</tbody>


The above throws the following error:


Could not parse the remainder: '[6]' from 'p[6]'


How do I access list items directly without looping through it?

Answer

You don't seem to be using Jinja at all here. Although Jinja is now an option in Django, the default is to use the built-in template language, and that appears to be what you are using. In that syntax, all lookups are done with dot notation:

 <td>{{ p.6 }}</td>

etc.