调用助手后无法访问数组元素(车把)

调用助手后无法访问数组元素(车把)

问题描述:

我已经在我的应用程序文件中注册了该帮助程序:

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);
});

然后,在我的hbs文件上:

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}}

但是,this.date不会输出任何内容,也不会调用date.如果不给助手打电话,我可以输出它.帮手有什么问题?

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?

问题是您使用的是hbs.registerHelper调用中的运算符/函数" rel ="nofollow noreferrer">函数表达式.重要的是要注意,箭头函数表达式不是 ,只是一种编写函数表达式的新颖方法;他们的表现不同.

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.

这种情况下的相关区别在于箭头函数表达式没有有自己的this对象.取而代之的是,他们获得了其封闭执行上下文的this.

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.

当您使用诸如hbs.registerHelper('if_greater', function (a, b, opts) { /*...*/ });之类的老式函数表达式定义Handlebars帮助器时,Handlebars会确保已执行的帮助器中的this是模板中的当前上下文.从文档中:

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:

把手总是在当前上下文为this的情况下调用帮助程序,因此您可以在this下调用该块以评估当前上下文中的块.

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.

但是,当您使用箭头函数表达式时,this来自定义函数的词法范围. this可能有很多东西,但不能成为您想要的模板上下文.

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.

有关箭头函数和函数表达式的详细概述,请参见: https://*.com/a/34361380/3397771

For a nice summary of arrow functions vs function expressions, see: https://*.com/a/34361380/3397771

要确认您的助手作为非箭头函数表达式编写时是否按预期工作,请参见此 fiddle .

For confirmation that your helper works as expected when written as a non-arrow function expression, see this fiddle.