在django模板中乘法,而不使用手动创建的模板标签 [英] multiplication in django template without using manually created template tag
问题描述
我有这个值,
price = 10.50
quantity = 3
借助这个链接
http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/
我尝试下面的代码实现它,
{%widthratio quantity 1 price%}
但只返回31.但是我需要在float(31.5)中的答案
我想实现它而不使用手动创建的标签
我该如何实现?
提前感谢...
有两种方法:
- 计算视图内的值并将其传递给模板(在我看来推荐)
- 使用模板过滤器
以 添加
过滤器,您可以随时创建自己的乘法
过滤器,创建自己的自定义过滤器:
def multiply(value,arg):
pre>
返回值* arg
然后在你的模板中,这样的东西应该可以工作。
{{quantity | multiply:price}}
,我从来没有做过再次 - 我发现更简单的在视图中计算数据,并使用模板渲染 。
I want to achieve multiplication operation in django template. For example I have the values, price=10.50 quantity=3
With the help of this link
http://slacy.com/blog/2010/07/using-djangos-widthratio-template-tag-for-multiplication-division/
i tried below codes for achieving it,
{% widthratio quantity 1 price %}
but its returning only 31. But i need the answer in float (31.5)
And i want to achieve it without using the manually created tags
How can i achieve it? Thanks in advance...
解决方案There are 2 approaches:
- Computing the values inside the view and pass them to the template (recommended in my opinion)
- Using template filters
In the manner of the add
filter, you could always create your own multiply
filter, creating your own custom filter:
def multiply(value, arg):
return value*arg
Then in your template, something like that should work.
{{ quantity|multiply:price }}
This is not tested, and I never did this as - again - I find neater to compute datas inside the views and render only with the templates.
这篇关于在django模板中乘法,而不使用手动创建的模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!