Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get odd and even values in a Django for loop template?

I have this code

{% for o in some_list %} 

Now I want to do some stuff if I am on an even line. How can I do that?

like image 317
tej.tan Avatar asked Jul 04 '11 13:07

tej.tan


People also ask

How do you sort data in a Django template?

To order them in the view I would need to iterate through the events and for each event create a container of some sort of the attendees related to that event in properly sorted order, then pass that entire collection of containers to the template in a form that would let the template find the appropriate collection of ...

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 is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


2 Answers

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#divisibleby

{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %} 
like image 146
mechanical_meat Avatar answered Sep 30 '22 01:09

mechanical_meat


In first level cycle:

{% cycle 'odd' 'even' %} 

Reference:

  • Documentation for cycle template tag
like image 45
Nikolay Fominyh Avatar answered Sep 29 '22 23:09

Nikolay Fominyh