How can i multiply data in nunjuncks?

旧巷老猫 提交于 2019-12-24 21:03:30

问题


for instance

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

i want to multiply price by quantity

data from Json file.


回答1:


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);



回答2:


There are multiple ways to do this, including building filters.

One simple way would be to define it in the template where you will use the value:

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

You could then say:

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

You could also then use this in the logic:

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

Finally you can just express it like this {{blocks.quantity*blocks.price}}, as previous commenter Sauntimo said already.




回答3:


You should be able to execute mathematical operations inside double curly braces like this:

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

See the docs at https://mozilla.github.io/nunjucks/templating.html#math



来源:https://stackoverflow.com/questions/53793721/how-can-i-multiply-data-in-nunjuncks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!