【问题标题】:calculating the sum over products of object attributes in jinja2计算jinja2中对象属性的乘积之和
【发布时间】:2017-05-24 22:30:38
【问题描述】:

我有一个名为“order”的对象,它具有“product.price”和“quantity”属性。我想计算所有订单的总成本。我将所有订单作为列表传递到模板中,我希望看到 jinja2 完成这项工作。

如果我只想计算所有价格的总和

${{ '%0.2f'| format(orders | sum(attribute='product.price')) }}

但是如何将乘法与数量属性相加?

【问题讨论】:

    标签: jinja2


    【解决方案1】:

    不确定有没有办法在一行中做到这一点。不过这可能有效:

    {% set totals = [] %}
    
    {% for order in orders %}
      {% if totals.append(order.product.price * order.quantity %}{% endif %}
    {% endfor %}
    
    ${{ '%0.2f' | format(totals | sum) }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 2015-09-20
      • 2016-10-12
      相关资源
      最近更新 更多