loop backwards using django template

Question:

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!

Asked By: still.Learning

||

Answers:

Directly from the page you linked:

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

Answered By: Joran Beasley

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

{% for obj in list | reverse %}
Answered By: Khizer Naeem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.