在Django模板中乘以-1 [英] Multiply by -1 in a Django template

查看:136
本文介绍了在Django模板中乘以-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  {%if qty> 0%} 
请销售{{qty}}个产品。
{%elif qty< 0%}
请购买{{-qty}}产品。
{%endif%}

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



有没有传递包含绝对值的第二个变量的解决方法?有些类似模板过滤器将值转换为无符号整数。



谢谢!

解决方案

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

  {%if qty> 0%} 
请销售{{qty}}个产品。
{%elif qty< 0%}
请购买{{qty | slice:1:}}产品。
{%endif%}

 请销售{{qty | stringformat:+ d| slice:1:}}产品。 

但您应该在您的视图中执行此操作或编写自定义过滤器。


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!

解决方案

You can abuse some string filters:

{% if qty > 0 %}
  Please, sell {{ qty }} products.
{% elif qty < 0 %}
  Please, buy {{ qty|slice:"1:" }} products.
{% endif %}

or

 Please, sell {{ qty|stringformat:"+d"|slice:"1:" }} products.

But you should probably do it in your view or write a custom filter.

这篇关于在Django模板中乘以-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆