乘以django模板 [英] Multiply in django template

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

问题描述

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

有可能做这样的事情吗?任何其他方式做到!谢谢

解决方案

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



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

  @ register.simple_tag()
def multiply(qty,unit_price,* args,** kwargs):
#你需要在这里做任何本地化的结果
return qty * unit_price

你可以这样称呼:

  {%load your_custom_template_tags%} 

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

您确定不想将此结果作为购物车项的属性吗?在您结帐时,您似乎需要这些信息作为购物车的一部分。


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.

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

@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

Which you can call like this:

{% 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天全站免登陆