Skip to content

Commit

Permalink
Merge pull request #289 from zinoviev/master
Browse files Browse the repository at this point in the history
Handlebars hash arguments as optional arguments support
  • Loading branch information
larzconwell committed Dec 21, 2012
2 parents 255b178 + a8637a1 commit 875bfb2
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
37 changes: 36 additions & 1 deletion lib/template/adapters/handlebars.js
Expand Up @@ -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) {
Expand All @@ -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;
13 changes: 13 additions & 0 deletions test/templates/engines/handlebars_mustache.js
Expand Up @@ -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());
}

};
Expand Down

0 comments on commit 875bfb2

Please sign in to comment.