for instance
<div class="price">{{blocks.quantity}} x {{blocks.price}} </div>
i want to multiply price by quantity
data from Json file.
for instance
<div class="price">{{blocks.quantity}} x {{blocks.price}} </div>
i want to multiply price by quantity
data from Json file.
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);
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.
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