[英]Handlebars Helpers in {{each}} block
I'm using Marionette and Handlebars, and so far I've been able to use the following template helper just fine: 我正在使用Marionette和Handlebars,到目前为止,我已经可以使用以下模板帮助程序了:
templateHelpers: function(){
return {
formatDate: function(dateString) {
var dateWithOffset = new Date(dateString);
var dateWithoutOffset = new Date(dateWithOffset.getTime() + dateWithOffset.getTimezoneOffset() * 1000 * 60);
return dateWithoutOffset.toLocaleDateString();
}
}
However, when I try to use it in my .hbs inside an {{each}} block I get an error. 但是,当我尝试在{{each}}块中的.hbs中使用它时,出现错误。
{{#each mi.Comments}}
{{formatDate date}}</br>
{{/each}}
mi.Comments does indeed have a date attribute and if I remove the formatDate, it displays the unformatted date properly for each comment. mi.Comments确实具有日期属性,如果我删除formatDate,它将为每个注释正确显示未格式化的日期。
Here is the error I get: 这是我得到的错误:
Uncaught Error: Missing helper: "formatDate"
Any guidance is appreciated. 任何指导表示赞赏。 This is part of a larger project with multiple other developers and I'm hoping to not use the HandleBars.registerHelper method, so I don't need to modify my base widget file.
这是与多个其他开发人员一起进行的较大项目的一部分,我希望不使用HandleBars.registerHelper方法,因此不需要修改基本的窗口小部件文件。
Turns out, when the {{#each}} block changes the context, it also changes the context for helper functions. 事实证明,当{{#each}}块更改上下文时,它也更改了辅助函数的上下文。 This code in the .hbs works:
.hbs中的此代码有效:
{{#each mi.Comments}}
{{../formatDate date}}</br>
{{/each}}
The '../' tells Handlebars to look at the parent of the current context, which is where the helper function resides. “ ../”告诉Handlebars查看当前上下文的父级,即辅助函数所在的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.