Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Handlebars.js helpers
/*! ******************************
Handlebars helpers
*******************************/
// debug helper
// usage: {{debug}} or {{debug someValue}}
// from: @commondream (http://thinkvitamin.com/code/handlebars-js-part-3-tips-and-tricks/)
Handlebars.registerHelper("debug", function(optionalValue) {
console.log("Current Context");
console.log("====================");
console.log(this);
if (optionalValue) {
console.log("Value");
console.log("====================");
console.log(optionalValue);
}
});
// return the first item of a list only
// usage: {{#first items}}{{name}}{{/first}}
Handlebars.registerHelper('first', function(context, block) {
return block(context[0]);
});
// a iterate over a specific portion of a list.
// usage: {{#slice items offset="1" limit="5"}}{{name}}{{/slice}} : items 1 thru 6
// usage: {{#slice items limit="10"}}{{name}}{{/slice}} : items 0 thru 9
// usage: {{#slice items offset="3"}}{{name}}{{/slice}} : items 3 thru context.length
// defaults are offset=0, limit=5
// todo: combine parameters into single string like python or ruby slice ("start:length" or "start,length")
Handlebars.registerHelper('slice', function(context, block) {
var ret = "",
offset = parseInt(block.hash.offset) || 0,
limit = parseInt(block.hash.limit) || 5,
i = (offset < context.length) ? offset : 0,
j = ((limit + offset) < context.length) ? (limit + offset) : context.length;
for(i,j; i<j; i++) {
ret += block(context[i]);
}
return ret;
});
// return a comma-serperated list from an iterable object
// usage: {{#toSentence tags}}{{name}}{{/toSentence}}
Handlebars.registerHelper('toSentence', function(context, block) {
var ret = "";
for(var i=0, j=context.length; i<j; i++) {
ret = ret + block(context[i]);
if (i<j-1) {
ret = ret + ", ";
};
}
return ret;
});
// format an ISO date using Moment.js
// http://momentjs.com/
// moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
// usage: {{dateFormat creation_date format="MMMM YYYY"}}
Handlebars.registerHelper('dateFormat', function(context, block) {
if (window.moment) {
var f = block.hash.format || "MMM Do, YYYY";
return moment(Date(context)).format(f);
}else{
return context; // moment plugin not available. return data as is.
};
});
@doginthehat

This comment has been minimized.

Copy link

@doginthehat doginthehat commented Feb 24, 2012

This slightly altered version of debug with show undefined if the passed value is undefined:

Handlebars.registerHelper("debug", function(optionalValue) {
  console.log("\nCurrent Context");
  console.log("====================");
  console.log(this);

  if (arguments.length > 1) {
    console.log("Value");
    console.log("====================");
    console.log(optionalValue);
  }
});
@robfletcher

This comment has been minimized.

Copy link

@robfletcher robfletcher commented Jun 12, 2012

There's a typo in the default date format at line 73: it should be "MMM Do, YYYY" (note Do rather than Mo)

@elidupuis

This comment has been minimized.

Copy link
Owner Author

@elidupuis elidupuis commented Jun 26, 2012

Thanks @robfletcher. Nice catch.

@atomsfat

This comment has been minimized.

Copy link

@atomsfat atomsfat commented Sep 12, 2012

Wow, nice

@spinegar

This comment has been minimized.

Copy link

@spinegar spinegar commented Feb 19, 2013

When passing a date to the helper I had to remove the Date Object from the helper.

return moment(context).format(f);

I also updated the helper to check if context has a truthy value and is indeed a valid date.

Handlebars.registerHelper('dateFormat', function(context, block) {
      if (window.moment && context && moment(context).isValid()) {
              var f = block.hash.format || "MMM Do, YYYY";
              return moment(context).format(f);
      }else{
              return context;   //  moment plugin is not available, context does not have a truthy value, or context is not a valid date
      }
});
@nataliebanegas

This comment has been minimized.

Copy link

@nataliebanegas nataliebanegas commented Feb 25, 2013

Date(args) returns current date. Needs to be invoked as a constructor: new Date(args) to set the desired date.

@samselikoff

This comment has been minimized.

Copy link

@samselikoff samselikoff commented Jul 31, 2013

Emberinos: use Ember.Handlebars.helper(... (an alias for Ember.Handlebars.registerBoundHelper).

registerHelper will just pass in the string.

@apt142

This comment has been minimized.

Copy link

@apt142 apt142 commented Nov 6, 2013

This is fantastic! One nitpick: toSentance is misspelled. It should be toSentence

@1st

This comment has been minimized.

Copy link

@1st 1st commented Apr 3, 2014

It's error here, need new for Date.

return moment(Date(context)).format(f);

replace to

return moment(new Date(context)).format(f);

@panser

This comment has been minimized.

Copy link

@panser panser commented Jun 10, 2015

I use this to wrap any data some function

Handlebars.registerHelper('runFunc', function(context, block) {
    var funcName = block.hash.fName;
    var resultCommand = funcName + '(' + context + ')';
    return eval(resultCommand);
});
function parseDate(data, format){
    if(data && window.moment && moment(data).isValid()) {
        var f = format || 'YYYY-MM-DD HH:mm:ss';
        return moment(data).format(f);
    }else{
        return data;
    }
}
{{runFunc annulationDate fName="parseDate"}}
@alexweissman

This comment has been minimized.

Copy link

@alexweissman alexweissman commented Sep 27, 2015

@spinegar's comment on the dateFormat helper is correct. It should be:

//  format an ISO date using Moment.js
//  http://momentjs.com/
//  moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
//  usage: {{dateFormat creation_date format="MMMM YYYY"}}
Handlebars.registerHelper('dateFormat', function(context, block) {
  if (window.moment) {
    var f = block.hash.format || "MMM Do, YYYY";
    return moment(context).format(f);
  }else{
    return context;   //  moment plugin not available. return data as is.
  };
});

Note that the Date wrapper on context is removed.

The SO thread on boolean logic helpers may also be of interest here: http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional/21915381#21915381

@crisanchez

This comment has been minimized.

Copy link

@crisanchez crisanchez commented Oct 21, 2015

Hello, somebody Do you have a example to convert string to number?.

thanks a lot

@GerardSmit

This comment has been minimized.

Copy link

@GerardSmit GerardSmit commented Aug 30, 2016

In Handlebars 4.0 I did get the error block is not a function when I tried to use the limit helper. This can be resolved by changing block to block.fn:

Handlebars.registerHelper('limit', function(context, block) {
    var ret = "",
        offset = parseInt(block.hash.offset) || 0,
        limit = parseInt(block.hash.limit) || 5,
        i = (offset < context.length) ? offset : 0,
        j = ((limit + offset) < context.length) ? (limit + offset) : context.length;

    for(i,j; i<j; i++) {
        ret += block.fn(context[i]);
    }

    return ret;
});
@mygittyhubby

This comment has been minimized.

Copy link

@mygittyhubby mygittyhubby commented Oct 17, 2017

where to put the Handlebars.registerHelper function ? which file ? I've been searching the internet and couldn't find the answer, I kept getting "Missing Helper" error messages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment