0

例如

 <div class="price">{{blocks.quantity}} x {{blocks.price}} </div>

我想将价格乘以数量

来自 Json 文件的数据。

4

3 回答 3

1

有多种方法可以做到这一点,包括构建过滤器。

一种简单的方法是在您将使用该值的模板中定义它:

{% set total_price = blocks.quantity * blocks.price %}

然后你可以说:

I will sell you {{ blocks.quantity }} apples for {{ blocks.price }} each, the 
total price will be {{ total_price }}.

然后,您也可以在逻辑中使用它:

{% if total_price > 100 %}
  Price per apple is {{ blocks.price }}
{% else %}
  Price per apple is {{ blocks.price * 0.9 }}
{% endif %}

最后,您可以像{{blocks.quantity*blocks.price}}之前的评论者 Sauntimo 所说的那样表达它。

于 2019-01-11T08:33:29.267 回答
0

您应该能够像这样在双花括号内执行数学运算:

<div class="price">{{blocks.quantity*blocks.price}}</div>

请参阅https://mozilla.github.io/nunjucks/templating.html#math上的文档

于 2018-12-15T15:26:18.820 回答
0
var nunjucks  = require('nunjucks');
var env = nunjucks.configure();

env.addFilter('mysum', function (arr) {
    return arr
        .map(e => e.quantity * e.price) // get amount to each e
        .reduce((sum, e) => sum + e, 0) // calc total summa
});

var data = [
    {price: 10, quantity: 2},
    {price: 2, quantity: 7},
    {price: 5, quantity: 11}
]

var res = env.renderString(`{{ data | mysum }}`, {data});

console.log(res);
于 2018-12-18T22:41:32.947 回答