Modulus % in Django template

underdoeg picture underdoeg · Dec 13, 2011 · Viewed 40.4k times · Source

I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.

With modulus it would look like this:

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

Of course this doesn't work because % is a reserved character. Is there any other way to do this?

Answer

Burhan Khalid picture Burhan Khalid · Dec 13, 2011

You need divisibleby, a built-in django filter.

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}