tag

If modulo template tag for Django

Posted by andu
Sun, 2007-08-05 13:28

Later edit: there's already a tag (and I should really check better next time) which does this. What this tag does extra, however, is allow you to check for the remainder as well.

In one of the projects at work I needed to compare the result of a modulo operation to another value in the template. Since the default Django tag library does not offer this kind of thing, I decided to write it.

Why would you need this kind of functionality? In my case I needed to output a list of items and put some markup after each 5 of them. I could have solved it by doing some magic in the views code but I did not want to mix the template logic with the views. And since I never wrote a template tag for Django, it looked like a nice opportunity.

You would use it like this:

  1. {% ifmodulo forloop.counter 4 0 %}
  2. <!-- do something -->
  3. {% else %}
  4. <!-- do something else -->
  5. {% endifmodulo %}

  1. {% ifnotmodulo 5 3 %}
  2. <!-- do something -->
  3. {% else %}
  4. <!-- do something else -->
  5. {% endifmodulo %}

Here's the code and you can also download the file by using the link at the bottom of this post: