Thursday, March 31, 2016

How to reference previous instance when looping in a template?

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fd318850-ac12-4abb-b6dd-62c0a3ee5b1b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment