Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

node.js - Can't access array element after calling helper (Handlebars)

I've registered this helper on my app file:

hbs.registerHelper('if_greater', (a, b, opts) => {
    if (a >= b) return opts.fn(this);
    return opts.inverse(this);
});

Then, on my hbs file:

{{#if_greater 20 occurrences}}
     <tr class="danger">
         <td>{{this.date}}</td>
         <td>{{this.serial}}</td>
         <td>{{this.operator}}</td>
         <td>{{this.vehicle}}</td>
         <td>{{this.stop}}</td>
         <td>{{this.line}}</td>
         <td>{{this.zone}}</td>
         <td>{{this.occurrences}}</td>
         <td>{{this.encrypted}}</td>
     </tr>
{{/if_greater}}

However, this.date doesn't output anything, neither does calling date. I can output it if I don't call my helper. What's wrong in the helper?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...