且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Django 模板中相乘

更新时间:2023-10-25 23:36:52

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

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.