Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply by -1 in a Django template

I'd like to always use a positive value of my variable in a Django template. The variable's sign is just a textual meaning:

{% if qty > 0 %}
  Please, sell {{ qty }} products.
{% elif qty < 0 %}
  Please, buy {{ -qty }} products.
{% endif %}

Of course, {{ -qty }} doesn't work.

Is there a workaround without passing a second variable containing the absolute value? Something like a template filter that would convert the value to an unsigned integer.

Thanks!

like image 866
alexpirine Avatar asked Apr 02 '13 18:04

alexpirine


1 Answers

As with everything in Python, there is a library for that: django-mathfilters.

Then you can simply use the abs filter like this:

Please, sell {{ qty|abs }} products.
like image 127
Krystian Cybulski Avatar answered Oct 09 '22 16:10

Krystian Cybulski