Skip to content

Instantly share code, notes, and snippets.

@tnguyen14
Last active August 29, 2015 14:13
Show Gist options
  • Save tnguyen14/288bc9936d1884596530 to your computer and use it in GitHub Desktop.
Save tnguyen14/288bc9936d1884596530 to your computer and use it in GitHub Desktop.
Handlebars helpers
var moment = require('moment');
var isString = require('amp-is-string');
Handlebars.registerHelper('date', function (date, format) {
var momentDate, formatStr;
// no date is passed in, default to current date
if ((date && date.data)) {
momentDate = moment();
} else {
// if the date passed in is not a moment type, convert it to moment
// otherwise use it
if (!moment.isMoment(date)) {
momentDate = moment(date);
// if the date parsing fails
if (!momentDate.isValid()) {
throw new Error('The date passed in is invalid');
}
} else {
momentDate = date;
}
}
// if no format string, default to 'MM/DD/YYYY'
formatStr = isString(format) ? format : 'MM/DD/YYYY';
return momentDate.format(formatStr);
};
Handlebars.registerHelper('ifeq', function (a, b, options) {
if (a === b) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper('log', function (stuff) {
console.log(stuff);
});
// step into context
// @param steps - the number of levels to go depeer into the context
function step (steps, options) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
if (steps === 1) {
return options.fn(this[key]);
} else {
step(steps-1);
}
}
}
};
Handlebars.registerHelper('step', step);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment