在django模板中乘法,而不使用手动创建的模板标签 [英] multiplication in django template without using manually created template tag

查看:121
本文介绍了在django模板中乘法,而不使用手动创建的模板标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在django模板中实现乘法运算。例如
我有这个值,
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):
返回值* arg
pre>

然后在你的模板中,这样的东西应该可以工作。

  {{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屋!

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