Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active February 15, 2021 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amatiasq/4944035 to your computer and use it in GitHub Desktop.
Save amatiasq/4944035 to your computer and use it in GitHub Desktop.
A simple RequireJS plugin to include Handlebars templates
define(function(require) {
var text = require('text');
var view = require('view');
var cache = {};
function load(name, parentRequire, done, config) {
text.load(name, parentRequire, function(template) {
cache[name] = template;
done(view(template));
}, config);
}
function write(pluginName, moduleName, write, config) {
write.asModule(pluginName + "!" + moduleName, [
"define([ 'view' ], function(view) {",
"return view('",
text.jsEscape(cache[moduleName]),
"');",
"});"
].join(""));
}
return {
load: load,
write: write,
};
});
define(function(require) {
var _ = require('underscore');
var Handlebars = require('handlebars');
/**************
* HANDLEBARS *
**************/
Handlebars.registerHelper('equals', function(value, expected, options) {
return Handlebars.helpers['if'].call(this, value == expected, options);
});
Handlebars.registerHelper('unless_equals', function(value, expected, options) {
return Handlebars.helpers['unless'].call(this, value == expected, options);
});
Handlebars.registerHelper('if_contains', function(value, expected, options) {
return Handlebars.helpers['if'].call(this, value && (value.indexOf(expected) !== -1), options);
});
Handlebars.registerHelper('unless_contains', function(value, expected, options) {
return Handlebars.helpers['unless'].call(this, value && (value.indexOf(expected) !== -1), options);
});
Handlebars.registerHelper('date', function(value, format) {
var date = typeof value === 'number' ? moment.unix(value) : moment(value);
if (format === 'from now')
return date.fromNow();
return date.format(typeof format === 'string' ? format : 'L')
});
/*****************
* VIEW FUNCTION *
*****************/
return function(text, callback) {
var compiled = Handlebars.compile(text);
return function(data) {
if (arguments.length > 1)
data = _.extend.apply(_, [{}].concat(_.toArray(arguments)));
return compiled(data ||   {});
};
};
});
@amatiasq
Copy link
Author

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