Skip to content

Supporting Handlebars subexpressions #224

Open
@tndev

Description

@tndev

I saw this question Handlebars subexpression throws “options.fn is not a function” error on stackoverflow:

The OP was asking why {{#and (gt 4 3) (gt 5 4)}}OK{{/and}} will throw a:

TypeError: options.fn is not a function

In the code it is obvious the helper requires fn and inverse (so an if/else) block:

helpers.gt = function(a, b, options) {
  if (arguments.length === 2) {
    options = b;
    b = options.hash.compare;
  }
  if (a > b) {
    return options.fn(this);
  }
  return options.inverse(this);
};

To support {{#and (gt 4 3) (gt 5 4)}}OK{{/and}} the helper should return true or false instead of options.fn(this) or options.inverse(this) if those blocks don't exists.

This might probably be a interesting feature. Or am I missing something here?

To support subexpressions the code could be changed to this:

helpers.gt = function(a, b, options) {
  if (arguments.length === 2) {
    options = b;
    b = options.hash.compare;
  }

  //fn block exists: it is not a subexpression
  if( options.fn ) {
     if (a > b) {
       return options.fn(this);
     }
     return options.inverse(this);
  } else { // otherwise return the result of the comparison
     return a > b;
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions