0

for instance

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

i want to multiply price by quantity

data from Json file.

Bravis
  • 91
  • 1
  • 9
  • I'm not sure why you messaged me on instagram, if you've got further questions can you post comments here? and if my answer helped, can you accept it so that people know this question is answered? – sauntimo Dec 15 '18 at 18:15
  • Sorry for that , i wrote down all about it here , still can't figure out how to do it . – Bravis Dec 16 '18 at 10:51
  • https://stackoverflow.com/questions/53788230/how-to-use-nunjucks-groupby-with-different-value – Bravis Dec 16 '18 at 10:52

3 Answers3

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);
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31
1

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.

Marma
  • 11
  • 1
0

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

sauntimo
  • 1,531
  • 1
  • 17
  • 28