How do I get odd and even values in a Django for loop template?
<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>
In first level cycle:
{% cycle 'odd' 'even' %}
Reference:
- Documentation for
cycle
template tag
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#divisibleby
{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}