multiplication in django template without using manually created template tag

后端 未结 3 1162
情歌与酒
情歌与酒 2020-12-09 16:46

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

h

3条回答
  •  無奈伤痛
    2020-12-09 17:15

    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:

    from django import template
    
    register = template.Library()
    
    @register.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.

提交回复
热议问题