user3799942
user3799942

Reputation: 289

django - multiplication and templates

I hope you can help me on this one. I have a template that shows the price of a, lets say a Banana, and for example the banana costs $400 and i have to calculate the 21% of this price and show it on a box of a table. I was tempted to do something like:

{% for banana in bananas %}
{{banana.price}}*(21%)
{% endfor %}

but obviously that failed miserably.

So, is there a way to do this type of simple equations in a template or i need to make a custom template tag to handle it.

its a very basic question but i would really appreciate the help.

Thank you.

Upvotes: 3

Views: 6859

Answers (2)

alecxe
alecxe

Reputation: 473853

You can use built-in widthratio template tag:

For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.

{% widthratio banana.price 100 21 %}

Upvotes: 1

Stephan
Stephan

Reputation: 3093

You do need a custom template tag, but you could install django-mathfilters, which provides such basic operations:

{% load mathfilters %}

...

{{banana.price|mul:0.21}}

Taken from the mathfilters page, the included operations are:

  • sub – subtraction
  • mul – multiplication
  • div – division
  • abs – absolute value
  • mod – modulo

'Add' is provided in Django as standard.

Upvotes: 11

Related Questions