在Django模板中乘以-1

ale*_*ine 8 django django-templates

我想在Django模板中始终使用我的变量的正值.变量的符号只是一个文本含义:

{% if qty > 0 %}
  Please, sell {{ qty }} products.
{% elif qty < 0 %}
  Please, buy {{ -qty }} products.
{% endif %}
Run Code Online (Sandbox Code Playgroud)

当然,{{ -qty }}不起作用.

有没有传递包含绝对值的第二个变量的解决方法?像模板过滤器那样将值转换为无符号整数的东西.

谢谢!

Pav*_*sov 12

你可以滥用一些字符串过滤器:

{% if qty > 0 %}
  Please, sell {{ qty }} products.
{% elif qty < 0 %}
  Please, buy {{ qty|slice:"1:" }} products.
{% endif %}
Run Code Online (Sandbox Code Playgroud)

要么

 Please, sell {{ qty|stringformat:"+d"|slice:"1:" }} products.
Run Code Online (Sandbox Code Playgroud)

但您应该在视图中执行此操作或编写自定义筛选器.


Kry*_*ski 5

与Python 中的所有内容一样,有一个库:django-mathfilters

然后你可以abs像这样简单地使用过滤器:

Please, sell {{ qty|abs }} products.
Run Code Online (Sandbox Code Playgroud)