How do we write math expressions in Blaze?

For example, I’d like to do math with the @index of the items in an {{#each}} block.F.e., this doesn’t work:

        {{#each result in results}}
          <div>{{@index * 20}}</div>
        {{/each}}

Is there a way without helpers?

Normally Spacebars doesn’t do expressions, but you could try {{#let}}
(Just a tip, never tried it that way myself…)

I may be mistaken but I think @index is deprecated. Regardless you could write a helper that takes each object, compares it with the origin array to grab the index, does the math, and returns the val to the template.

@index is supported and documented: http://docs.meteor.com/packages/spacebars.html#Each

1 Like

That’s an advantage with React then, that we can write math expressions, etc.

https://github.com/raix/Meteor-handlebar-helpers has a feature called “$.javascript” helpers where you can create some function and place that function in the helper scope so that you can use it in your templates. I think it is the closest you can get.

I just created a Meteor package:

meteor add manuelro:blaze-math

https://atmospherejs.com/manuelro/blaze-math


If all you need are basic operations with two members, then create a very simple helper for this.

Helper

Template.registerHelper( 'math', function () {
  return {
    mul ( a, b ) { return a * b; },
    div ( a, b ) { return b ? a / b : 0; },
    sum ( a, b ) { return a + b; },
    sub ( a, b ) { return a - b; },
  }
} );

Usage

<template name="myTemplate">
    {{ math.sum 3 5 }}
    <!-- 8 -->
</template>

N number of terms

Template.registerHelper( 'math', function () {
  let result = ( terms, cb ) => terms.pop() && terms.reduce( cb );

  return {
    mul ( ...terms ) { return result( terms, ( a, b ) => a * b ); },
    div ( ...terms ) { return result( terms, ( a, b ) => b ? a / b : 0 ); },
    sum ( ...terms ) { return result( terms, ( a, b ) => a + b ); },
    sub ( ...terms ) { return result( terms, ( a, b ) => a - b ); },
  }
} );

Usage

<template name="myTemplate">
    {{ math.mul 3 5 2 }}
    <!-- 30 -->
</template>
2 Likes