How to reference previous instance when looping in a template?

10 views
Skip to first unread message

Richard Brockie

unread,
Mar 31, 2016, 10:49:07 AM3/31/16
to Django users
Hi,

I'm doing a lot of this type of looping in my templates (from the docs: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for):
<ul>
{% for athlete in athlete_list %}
   
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>

In this context, I find myself occasionally wanting to refer to data of the previous athlete (if the instance exists) while working on the current athlete.

The way I do this right now is within a custom template tag. I copy the data of interest into a session variable for use next time the custom template tag is called. This works, but I'm wondering if there is a better way?

My thought was the following: what if there existed a .previous property attached to the current instance that contains the previous instance for this purpose?

IE:

<ul>
{% for athlete in athlete_list %}
   
<li>This time: {{ athlete.name }}, last time: {{ athlete.previous.name }}</li>
{% endfor %}
</ul>

athlete.previous would obviously be None the first time round the loop.
Reply all
Reply to author
Forward
0 new messages