Modulo In Django Templates

Ever find yourself wishing for the modulo operator (%) in Django templates? I did. Its easy enough to create your own custom filter so why not do it?

Caveat: I couldn't figure out how to get the filter to accept two arguments to do the modulo test against so I defaulted the test value to zero. If there is a way to add a second argument I would love to add that to the code.

In the templatetags directory of your Django install, add a file named 'mod.py'. In that file add the following code:

from django import template
register = template.Library()

def mod(value, arg):
    if value % arg == 0:
        return True
    else:
        return False

register.filter('mod', mod)

In your template use the mod filter like this:

...
{% load mod %}
...
<tr bgcolor="{% if forloop.counter|mod:2 %}#cccccc{% else %}#ffffff">
...

This will alternate every other row's background color between gray and white.

Comments
Just what I was looking for, thanks.
# Posted By anon | 1/31/08 7:34 AM
You could also try:
<tr bgcolor="{% cycle #ccc,#fff %}">
or
<tr class="{% cycle odd,even %}">
# Posted By Eoghan Murray | 4/15/08 3:37 AM
It's been a while, so don't know if you're still interested, but the 'divisibleby' filter is exactly what you're looking for. It lets you do something like this:

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

Which is equivalent to your '|mod:2'.
# Posted By Josh | 7/11/08 8:13 AM
# Posted By UGG | 1/19/10 11:51 PM
# Posted By ugg boots | 1/28/10 1:33 AM
# Posted By air max | 3/10/10 7:36 PM