如何在自定义帮助程序块中呈现Handlebars变量? [英] How can one render Handlebars variables inside a custom helper block?
问题描述
我正在尝试获取两个Handlebars变量,以在我创建的自定义Handlebars助手中进行渲染.
I'm trying to get two Handlebars variables to render inside a custom Handlebars helper I've created.
我正在使用Express.js视图引擎处理handlebars.js,并在我的 app.js
中设置了一个用于比较相等性的助手:
I'm using the Express.js view engine for handlebars.js, and in my app.js
have set up a helper to compare equality:
const hbs = require('hbs');
app.set('view engine', 'hbs');
hbs.registerHelper('ifEqual', (a, b, options) => {
if (a === b) {
return options.fn(this);
}
return options.inverse(this);
});
我的控制器将两个变量传递给视图:
My controller passes two variables to the view:
res.render('my-view', {
x: 3,
y: 3,
});
在 my-view.hbs
中,如果变量相等,我想渲染变量,所以我尝试:
In my-view.hbs
I'd like to render the variables if they're equal, so I tried:
{{#ifEqual x y}}
foo
{{x}}
{{y}}
{{/ifEqual}}
结果仅渲染 foo
.为什么 {{x}}
和 {{y}}
在这里不显示?我需要做一部分吗?
The result is only foo
renders. Why don't {{x}}
and {{y}}
render here? Do I need to do this with a partial?
推荐答案
模板不会在内部呈现
块是因为该块的上下文中没有 x
或 y
值的原因ifEqual x
或 y
属性.上下文中缺少这些属性的原因很简单:这是因为在调用 registerHelper
时,您使用了箭头函数表达式来定义Helper函数.
The reason your template will not render the values of x
or y
from within your ifEqual
block is because there are no x
or y
properties within the context of that block. The reason that these properties are missing from the context is a very simple one: It is because in your call to registerHelper
you used an Arrow Function Expression to define the Helper function.
箭头函数表达式,在除了更紧凑的语法外,还与标准函数表达式不同.在这种情况下,重要的区别在于它们没有自己的 this
上下文.
Arrow Functions Expressions, in addition to a more compact syntax, are different from standard Function Expressions. The important difference in this case is that they do not have their own this
context.
当您调用 registerHelper
时,Handlebars将把辅助回调函数绑定到模板的数据上下文,在这种情况下,它将是Object: {x:3,y:3}
.但是,这仅在您使用常规函数表达式作为回调并且不是箭头函数表达式的情况下有效-因为箭头函数表达式不能动态绑定到其他此
上下文.
When you call registerHelper
, Handlebars will bind the helper callback function to the data context of the template, in this case that would be the Object: { x: 3, y: 3 }
. However, this will only work if you use a regular Function Expression as your callback and not an Arrow Function Expression - as the Arrow Function Expression cannot be dynamically bound to a different this
context.
这意味着您必须使用正则函数表达式作为 registerHelper
的参数:
This means that you must use a regular function expression as your argument to registerHelper
:
hbs.registerHelper('ifEqual', function (a, b, options) {
// Function body remains the same.
});
要更好地了解问题所在,可以在助手中使用两种函数表达式类型 console.log(this)
并比较差异.
To get a better sense of what is wrong, you could console.log(this)
within your helper using both function expression types and compare the difference.
我已经创建了一个小提琴来演示这种差异.
I have created a fiddle to demonstrate the difference.
这篇关于如何在自定义帮助程序块中呈现Handlebars变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!