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!
Answers:
Directly from the page you linked:
You can loop over a list in reverse by using {% for obj in list reversed %}
.
In case someone ends up here looking for jinja2 solution, like me:
{% for obj in list | reverse %}
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!
Directly from the page you linked:
You can loop over a list in reverse by using {% for obj in list reversed %}
.
In case someone ends up here looking for jinja2 solution, like me:
{% for obj in list | reverse %}