Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 636
still.Learning Avatar asked Oct 01 '12 20:10

still.Learning


People also ask

How do I reverse a loop in Django?

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

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

Does Django have template?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


2 Answers

Directly from the page you linked:

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

like image 86
Joran Beasley Avatar answered Oct 02 '22 14:10

Joran Beasley


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

{% for obj in list | reverse %} 
like image 38
Khizer Naeem Avatar answered Oct 02 '22 14:10

Khizer Naeem