Using Django’s widthratio template tag for multiplication & division.

I find it a bit odd that Django has a template filter for adding values, but none for multiplication and division. It’s fairly straightforward to add your own math tags or filters, but why bother if you can use the built-in one for what you need?

Take a closer look at the widthratio template tag. Given {% widthratio a b c %} it computes (a/b)*c

So, if you want to do multiplication, all you have to do is pass b=1, and the result will be a*c.

Of course, you can do division by passing c=1. (a=1 would also work, but has possible rounding side effects)

Note: The results are rounded to an integer before returning, so this may have marginal utility for many cases.

So, in summary:

to compute A*B: {% widthratio A 1 B %}
to compute A/B: {% widthratio A B 1 %}

And, since add is a filter and not a tag, you can always to crazy stuff like:

compute A^2: {% widthratio A 1 A %}
compute (A+B)^2: {% widthratio A|add:B 1 A|add:B %}
compute (A+B) * (C+D): {% widthratio A|add:B 1 C|add:D %}

7 thoughts on “Using Django’s widthratio template tag for multiplication & division.”

  1. Clever! I can’t remember the last time I wanted to do multiplication or division in a template, but I’ll file this trick away for future reference.

  2. See: – its clear the developers don’t want these kinds of tags in the “core”.

    I doubt it will be long before someone develops a “customisable tag library” along the lines of the way jQuery works – where you click on the modules you want and they get built into a downloadable file. If this has been already, please let me know. If not, you saw the idea here first!

Leave a Reply