Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the options parameter in a Handlebars helper function?

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;
});
like image 504
Blake Avatar asked Jul 07 '14 08:07

Blake


1 Answers

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];
like image 87
doowb Avatar answered Oct 02 '22 22:10

doowb