Skip to content

Instantly share code, notes, and snippets.

@sylvaindethier
Last active August 29, 2015 14:01
Show Gist options
  • Save sylvaindethier/411fa0f4e82f0519e180 to your computer and use it in GitHub Desktop.
Save sylvaindethier/411fa0f4e82f0519e180 to your computer and use it in GitHub Desktop.
Handlebars helpers
/**
* MomentJS - fromNow
*/
Handlebars.registerHelper('moment_unix_fromNow', function (timestamp) {
return moment.unix(timestamp).fromNow();
});
/**
* Replace \n by <br />, such as the `nl2br` in PHP
* @see http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent
*/
Handlebars.registerHelper('nl2br', function (text, isXhtml) {
var breakTag = (isXhtml || typeof isXhtml === 'undefined') ? '<br />' : '<br>';
return (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
});
/**
* Pluralization outputs singular or plural given a value
*/
Handlebars.registerHelper('pluralize', function (value, singular, plural) {
return value > 1 ? plural : singular;
});
/**
* Extend context w/ object before 'each' iteration
*/
Handlebars.registerHelper('eachExtend', function (context, object, options) {
if ((context && 'object' === typeof context) && (object && 'object' === typeof object)) {
//@TODO: implement functions in native JavaScript
jQuery.each(context, function (i) {
// extends context@i w/ object
context[i] = jQuery.extend(true, context[i], object);
});
}
// perform Handlebars #each on context
return Handlebars.helpers.each(context, options);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment