Tuesday, February 5, 2013

MULTIPLICATION AND DIVISION IN DJANGO TEMPLATES

Django only provides with the built-in add tag. It means if you have to subtract something you have to use the same add tag. Generally it is recommended that you should do maths operations in the views. but if you want to do it in templates then there are two ways
  1.  Write you own template tag that should receive arguments and return results. That is also easy you have to have a template tag directory in you apps and settings file. To find more on that follow this link.
  2. The other is to follow this post. It will let you know how to multiply and divide without creating your own template tags.
 Lets start with a simple add example.
{{ list.item |add:"10" }}
will return the result by adding item and 100
item + 10 is equivalent to {{ list.item |add:"10" }}
If you want to subtract then 
{{ list.item |add:"-10" }}
will return the result by adding -100 to item
item - 10 is equivalent to {{ list.item |add:"-10" }} 
Now comes the tricky part,  if you want to multiply or divide then???

Its easy. You need to take a look at the widthratio tag. It takes 3 arguments. Now you have to play around with this tag.
Normally it is like
{% widthratio X Y Z %}
How it is evaluated?
         It is evaluated like X/Y*Z. Now if you want to Multiply supply Y as 1 so it would be X/1 * Z that evaluates to X*Z. Similarly if you want to divide than supply Z as 1 it would evaluate to X/Y * 1 which has no effect on the result.
In short
To Compute A*B:
{% widthratio X 1 Z %}
To Compute A/B:

{% widthratio A B 1 %}
In templates you usually have lists upon which you are iterating or any other data structure. so you need to replace the variable with you variables or items and example of that would be
{% for list in temp_list %}
        {% widthratio list.price 1 list.books %} 
{% endfor %} 
This will multiply the price with the books by iterating over this list.

To demonstrate the combined use use of add and multiplication the example is demonstrated below:
compute (P+Q) * (R+S): {% widthratio P|add:Q 1 R|add:S %}









No comments:

Post a Comment