[Fixed]-Django template forloop.counter question

24👍

The cycle tag is designed for this type of problem:

{% for field in form %}
    <li class="{% cycle 'thiscolor' 'thatcolor' %}">{{ field }}</li>
{% endfor %}

21👍

I agree with Jarret that cycle is best here, but to actually answer the question, the %2==0 operation can be replicated by using the divisibleby filter.

{% if forloop.counter|divisibleby:"2" %}

1👍

Another thing to keep in mind is that since this is a front end problem – the styling is what you’re trying to effect – you can solve it on the front end. There’s a good example provided toward the bottom of this A List Apart article. Of course, if you’ve already got working Django code there’s no sense in doing this now.

Leave a comment