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

DjangoDjango Templates

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

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

{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}

Solution 2 - Django

In first level cycle:

{% cycle 'odd' 'even' %}

Reference:

Solution 3 - Django

<div class="row">
{% for post in posts %}
      {% cycle 'odd' 'even' %}
      {% if cycle == 'odd' %}
        <div class="col-md-6">Odd posts</div>
      {% else %}
        <div class="col-md-6">Even posts</div>
      {% endif %}
    {% endfor %}
</div>

OR

<div class="row">
{% for post in posts %}
   {% if forloop.counter|divisibleby:2 %}
        <div class="col-md-6">Even posts</div>
      {% else %}
        <div class="col-md-6">Odd posts</div>
      {% endif %}
    {% endfor %}
</div>

Solution 4 - Django

<div class="row">
{% for post in posts %}
   {% if loop.index is divisibleby 2 %}
        <div class="col-md-6">Even posts</div>
      {% else %}
        <div class="col-md-6">Odd posts</div>
      {% endif %}
    {% endfor %}
</div>

http://mitsuhiko.pocoo.org/jinja2docs/html/templates.html#id3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontej.tanView Question on Stackoverflow
Solution 1 - Djangomechanical_meatView Answer on Stackoverflow
Solution 2 - DjangoNikolay FominyhView Answer on Stackoverflow
Solution 3 - Django7guyoView Answer on Stackoverflow
Solution 4 - DjangoZoltan FedorView Answer on Stackoverflow