我如何在 nunjucks 中乘以数据?

How can i multiply data in nunjuncks?

例如

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

我想用数量乘以价格

来自 Json 文件的数据。

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

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

请参阅 https://mozilla.github.io/nunjucks/templating.html#math

中的文档
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);

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

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

{% 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所说。