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.
![[link:home]](http://thebuckpasser.com/images/home.png)
![[link:about me]](http://thebuckpasser.com/images/aboutme.png)
![[link:rankings]](http://thebuckpasser.com/images/rankings.png)



<tr bgcolor="{% cycle #ccc,#fff %}">
or
<tr class="{% cycle odd,even %}">
{% if forloop.counter|divisibleby:"2" %}
Which is equivalent to your '|mod:2'.