What is the options parameter in a Handlebars helper function?
Asked Answered
N

1

9

I am creating a custom handlebar helper but it always throws Object #<Object> has no method 'fn' when compiled through the terminal.

My handlebar helper is:

module.exports.register = function (Handlebars, opts, params)  { 
    Handlebars.registerHelper('compimg', function (context, opts)  { 
        var compImg = ["assets/img/icon-nope.png","assets/img/icon-check.png"];
        return compImg[opts.fn(context)];
    });
}

My .hbs file is:

{{#each checkable}}
   <div class="col-md-3 col-xs-3 icon-container"><img src="{{compimg this}}"></div>
{{/each}}

My JSON file is:

{
    "desc": "blablabla",
    "checkable": [
        1,
        1,
        1,
        1
    ]
}

When I checked the official documentation I found this piece of code. Can someone explain what exactly context and options are here?

Handlebars.registerHelper('each', function(context, options) {
  var ret = "";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + options.fn(context[i]);
  }

  return ret;
});
Natation answered 7/7, 2014 at 8:44 Comment(0)
D
10

The handlebars example for each is a block helper, which means that there is more markup or template syntax between the {{#each}} and {{/each}} tags. When you use this syntax, Handlebars passes an options parameter to your helper as the last argument. The options object contains a fn method that works just like a compiled template... var html = options.fn(context); gives you the rendered template from inside the block.

The context variable is the thing that you're passing into your helper and can be any number of arguments if you want more.

Since you're making an inline helper and a not a block helper, I think you only need to change one line...

return compImg[opts.fn(context)];

to

return compImg[context];
Domiciliary answered 7/7, 2014 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.