Tag Archives: node.js

Handlebars Helper: SUM

Handlebars.js mustache logo
Handlebars.js

Here simple Handlebar-js snippet for returning the sum of unknown number of arguments pass to helper.

Parameters: none.

/**
 * Sum
 * Returns the sum of n item.
 */
Handlebars.registerHelper('sum', function() {
      var sum = 0, v;
      for (var i=0; i<arguments.length; i++) {
        v = parseFloat(arguments[i]);
        if (!isNaN(v)) sum += v;
      }
      return sum;
    });

Usage:

{{sum context.value1 context.value2 context.value3}}

Example:

Context:

var context = {facebook: 67, twitter: 80, plus: 13}

Template:

<div class="social-count">{{sum context.facebook context.twitter context.plus}}</div>

Results:

<div class="social-count">60</div>