在 Django 模板中相乘 [英] Multiply in django template

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

问题描述

我正在遍历购物车项目,并希望像这样将数量与单价相乘:

I am looping through cart-items, and want to multiply quantity with unit-price like this:

{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}

有没有可能做这样的事情?任何其他方式来做到这一点!谢谢

Is it possible to do something like that? any other way to do it !! Thanks

推荐答案

您需要使用自定义模板标签.模板过滤器只接受一个参数,而自定义模板标签可以根据需要接受任意数量的参数,进行乘法并将值返回给上下文.

You need to use a custom template tag. Template filters only accept a single argument, while a custom template tag can accept as many parameters as you need, do your multiplication and return the value to the context.

您需要查看 Django 模板标签文档,但一个简单的例子是:

You'll want to check out the Django template tag documentation, but a quick example is:

from django import template
register = template.Library()

@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
    # you would need to do any localization of the result here
    return qty * unit_price

你可以这样称呼:

{% load your_custom_template_tags %}

{% for cart_item in cart.cartitem_set.all %}
    {% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}

您确定不想将此结果作为购物车项目的属性吗?当您结账时,您似乎需要将此信息作为购物车的一部分.

Are you sure you don't want to make this result a property of the cart item? It would seem like you'd need this information as part of your cart when you do your checkout.

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

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