still.Learning
still.Learning

Reputation: 1245

loop backwards using django template

I have a list of objects and I am trying to display them all (and so I am using the django {% for %} {% endfor %}) However, I need to iterate through each object backwards one at a time, rather than forwards. I've looked at https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for but I couldn't really figure out how I can use it to loop backwards. I was wondering how to do this and if it is even possible. Below is a simple example of how I currently have it implemented (iterating forward):

...
{% for i in scheduling_info %}
    <pre>{{ i.log }}</pre>
{% endfor %}
...

Thanks!

Upvotes: 57

Views: 30102

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113988

Directly from the page you linked:

You can loop over a list in reverse by using {% for obj in list reversed %}.

Upvotes: 147

Khizer Naeem
Khizer Naeem

Reputation: 189

In case someone ends up here looking for jinja2 solution, like me:

{% for obj in list | reverse %}

Upvotes: 18

Related Questions