Multiply by -1 in a Django template

泄露秘密 提交于 2020-01-02 01:53:06

问题


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!


回答1:


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.




回答2:


You should use a custom filter for this.

Here's two different ways to do it:

1) You can define a negate filter:

# negate_filter.py
from django import template
register = template.Library()

@register.filter
def negate(value):
    return -value

Then in your template, add the code {% load negate_filter %} to the top and then replace {{ -qty }} with {{ qty|negate }}.

2) You can also replace the entire thing with one buy_sell filter if you'd like:

# buy_sell_filter.py
from django import template
register = template.Library()

@register.filter
def buy_sell(value):
    if value > 0 :
      return 'sell %s' % value
    else :
      return 'buy %s' % -value

Then your template should just be

{% if qty %} Please, sell {{ qty|buy_sell }} products.{% endif %}

You could even include the entire string in the filter and just have then entire template be {{ qty|buy_sell }}.

Both options are reasonable, depending on the rest of your template. For example, if you have a lot of strings that use buy for negative and sell for positive, do the second one.




回答3:


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.



回答4:


Ideally you would perform the check in your view, to separate logic from display (for example, what happens if qty = 0?) If you insist on doing math in the template, you could do something like this hack.

Another option is to write a custom filter (see this example).



来源:https://stackoverflow.com/questions/15771973/multiply-by-1-in-a-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!