The issue is that you are using an arrow function expression rather than a function expression in your hbs.registerHelper
call. It's important to note that arrow function expressions are not simply a neat new way for writing function expressions; they behave differently.
The relevant difference in this case is that arrow function expressions do not have their own this
object. Instead, they get the this
of their enclosing execution context.
When you define a Handlebars helper with an old-fashioned function expression, like hbs.registerHelper('if_greater', function (a, b, opts) { /*...*/ });
, Handlebars takes care of ensuring that the this
within the executed helper is the current context in your template. From the docs:
Handlebars always invokes helpers with the current context as this
, so you can invoke the block with this
to evaluate the block in the current context.
However, when you use an arrow function expression, the this
comes from the lexical scope in which the function is defined. this
can be a lot of things, but it cannot be the template context that you want.
For a nice summary of arrow functions vs function expressions, see: https://stackoverflow.com/a/34361380/3397771
For confirmation that your helper works as expected when written as a non-arrow function expression, see this fiddle.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…