Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #289 from zinoviev/master

Handlebars hash arguments as optional arguments support
  • Loading branch information...
commit 875bfb28670d70cb95545851c94d9a82a719fe31 2 parents 255b178 + a8637a1
@larzconwell larzconwell authored
View
37 lib/template/adapters/handlebars.js
@@ -49,7 +49,7 @@ Handlebars.prototype.registerHelper = function (name, helper) {
return false;
}
- this.engine.registerHelper(name, helper);
+ this.engine.registerHelper(name, this.wrapOptions(helper));
};
Handlebars.prototype.registerHelpers = function (helpers) {
@@ -62,4 +62,39 @@ Handlebars.prototype.registerHelpers = function (helpers) {
}
};
+/*
+ * In erj we can simple call function passing options hash
+ * as argument in template, but for for handlebars it's impossible,
+ * cause object hash is not mustache expression
+ *
+ * We can use optional has arguments in handlerbars for this,
+ * but will be passed inside wrapped option object {hash : { foo : 'bar', baz : 'bla' }}
+ * and template helpers in /template/helpers like urlFor
+ * is not intended to work with this. So we just unpack options and pass them
+ * to regular helper function and we can keep one set helpers with optional arguments
+ * for handlebars and other engines
+ */
+
+Handlebars.prototype.wrapOptions = function (helper) {
+ return function() {
+ var argsLen = arguments.length,
+ options = argsLen ? arguments[argsLen - 1] : null,
+ i = 0 , newArgs;
+
+ if (options && options.hash) {
+ newArgs = [];
+
+ for (;i<argsLen - 1; i++) {
+ newArgs.push(arguments[i]);
+ }
+
+ newArgs.push(options.hash);
+ return helper.apply(this, newArgs);
+ }
+ else {
+ return helper.apply(this, arguments);
+ }
+ }
+}
+
module.exports = Handlebars;
View
13 test/templates/engines/handlebars_mustache.js
@@ -80,6 +80,19 @@ tests = {
var html = '<p>foo</p>',
str = '<p>{{#items}}{{foo}}{{/items}}</p>';
assert.equal(html, render(str, {items: [{foo: 'foo'}]}));
+ },
+
+ 'test hash arguments' : function () {
+ var html = 'foobar.com/main/index'
+ , tpl = "{{url host='foobar.com' controller='main' action='index'}}"
+ , helper = function(options) {
+ console.log(options);
+ return options.host + '/' + options.controller + '/' + options.action
+ }
+
+ var adapter = new Adapter({engine: 'handlebars', template: tpl});
+ adapter.registerHelper('url', helper);
+ assert.equal(html, adapter.render());
}
};
Please sign in to comment.
Something went wrong with that request. Please try again.