Could I sum of "price" in template "{{#each data}}"?

I would like to sum of amount with spacebar in {{#each data}} like this

<template name="myTpl">
   <ul>
   {{#each data}}
      <li>{{item}} | {{qty}} | {{price}} | {{amount}}
       // calculate sum of amount
   {{/each}}
   </ul>
   Total {{sum of amount}} // echo sum that calculate above
</template>

Template.myTpl.helpers({
  data: function(){
    return data; // array of object
  }
})

I’d store the sum on the data collection itself. You can take advantage of Mongo’s collection transform to calculte the sum on the server side.

in meteor 1.2 u can use let to set variables

what do you mean by this?

I’m not 100% sure, but can’t you just do something like this?

Notice the {{total}} helper.
You where also missing the closing </li>

<template name="myTpl">
   <ul>
       {{#each data}}
          <li>{{item}} | {{qty}} | {{price}} | {{amount}}</li>
           // calculate sum of amount
       {{/each}}
   </ul>
   Total {{total}} // echo sum that calculate above
</template>

Be sure to replace the “myCollection” with your collection.

Template.myTpl.helpers({
    data: function(){
        return data; // array of object
    },
    total: function() {
        var sum = 0;
        var cursor = MyCollection.find();

        cursor.forEach(function(doc){
            sum = sum + doc.price
        });

        return sum; // return total
    }
});

Hope this helps.

1 Like

When you use each, it changes the context of this to be the current item you’re iterating over. Therefore, you can use a helper.

Template.yourTemplate.helpers({
  total: function () {
    return this.qty * this.price * this.amount;
  }
});
1 Like

Thanks for all reply. I tried to use

var sum = 0;
        var cursor = MyCollection.find();

        cursor.forEach(function(doc){
            sum = sum + doc.price
        });

        return sum; // return total

but I think that it is slow ,if I have many records (because it loop twice).

It is not so slow. Do not afraid of Collection.find() or .find().fetch() in helpers. You just should worry about a huge rerenders on a client side because of the main realy slow thing is DOM manipulation.

I do this on the Meteor.method() to generate report.

I suggest you use collection hooks on the server side to calculate the sums for your documents and store it in each document.