Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to `bind` a handlebars helper before render? (using express & hbs)

I've got a helper called feature that looks like this:

hbs.registerHelper('feature', function(request, flag, options) {
  if (features(flag, request)) {
    return options.fn(this);
  } else if (options.inverse) {
    return options.inverse(this);
  }
});

And used in the template over and over like this:

{{feature request "some-feature"}} ... {{/feature}}

I'd love to be able to remove the request part in the template as it's always the same value and never changes. So I imagine I could bind request to feature when it's rendered, and obviously that changes each time and I don't want it spilling out to other request.

Something like:

res.render("page", {
  feature: hbs.helper.feature.bind(null, req)
});

Is this possible?

like image 394
Remy Sharp Avatar asked Feb 23 '14 18:02

Remy Sharp


1 Answers

If you are not using known helpers mode then the helper evaluation will check the context so you can pass in a bind like you have above and it should work.

Under the latest code in handlebars master the eval is something like:

helper = helpers.foo || (depth0 && depth0.foo) || helperMissing
helper.call(depth0, 1, {"name":"foo","hash":{},"data":data}

Where depth0 is the current context object. The caveat here is that helpers are given priority so you need to name them differently. You should also be able to do something like {{./foo bar}} to give priority to the local context's version but it appears that we have a bug where that isn't honored under this particular syntax construct.

like image 72
Kevin Decker Avatar answered Oct 05 '22 13:10

Kevin Decker