Search code examples
handlebars.js

Passing expression to handlebars custom helper


New to handlebars, I've registered a helper and I can´t figure out what seems to be a simple task: how to pass an expression to handlebars helper.

Let's say:

Handlebars.registerHelper('or', function (v1, v2) {
  return (v1 || v2) ? options.fn(this) : options.inverse(this);
}

And when using it:

{{#conditional @index this.warranty_id !== "DEFAULT_FACTORY" }}

Of course it fails, and I can't figure out how make it work. What I need is that the expression being passed returns a boolean to be the v2 value inside the helper.

Any help will be appreciated.


Solution

  • You need to write a helper to check for !== and then nest it as a subexpression inside your or helper.

    OR helper

    Handlebars.registerHelper('or', function (v1, v2) {
      return (v1 || v2) ? options.fn(this) : options.inverse(this);
    }
    

    !== helper

    Handlebars.registerHelper('ne', function (v1, v2) {
      return (v1 !== v2); 
    }
    

    and then in your template:

    {{#or @index (ne this.warranty_id "DEFAULT_FACTORY")}}