Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do some simple math in Meteor's template?

Let's say I have a simple product_orders collection in Meteor (_id, user_id, user_name, product_name, price_unit, quantity) and I want to show all orders of a single user in table where each row should contain:

user_name, product_name, quantity, price_unit, quantity, price_total (price_unit * quantity)

Additionally I would like to display a grand total for all user's orders.

I don't see easy way to do this in Handlebars.js template as Handlebars doesn't appear to support simple math operations. I can easily return product_order's cursor to my template but don't see easy way to calculate price_total and grand total in template.

I am thinking of creating a template helper of some sort but not sure if that's the proper direction to go. This problem looks like it must have a simple & elegant solution.

like image 511
vladimirp Avatar asked Jan 20 '13 15:01

vladimirp


1 Answers

Yes, you should write a helper. Handlebars doesn't support using logic in the templates (which is a good practice as it forces you to apply the separation of concerns pattern).

A template helper looks like this:

Handlebars.registerHelper("grandTotal", function(user_name) {
  var grandTotal = some_magic_to_calc_total(user_name);
  return grandTotal;
});

Then you can call the helper like this from your template:

<template name="foo">
  {{grandTotal user_name}}
</template>

You can read more about helpers in the Handlebars.js docs.

like image 109
Rahul Avatar answered Oct 28 '22 18:10

Rahul