[英]Handlebars.js helper in #each loop returns same results?
我正在嘗試在#each循環中使用車把注冊的momentjs助手格式化日期。 注冊的幫助程序如下所示:
Handlebars.registerHelper('dateFormat', function(context) { if (window.moment) { return moment(Date(context)).format("MMM Do, YYYY"); }else{ return context; }; });
車把循環看起來像這樣
{{#每個控制器}}
{{{身體}}}
{{{dateFormat date}}}
{{/每}}
正在循環的JSON在此
{ "idea":[ { "_id":"548eeebeda11ffbe12000002", "body":"cow", "tag":"cow", "date":"2014-12-15T14:22:54.088Z" }, { "_id":"548eeec2da11ffbe12000003", "body":"cow", "tag":"moose", "date":"2014-10-15T14:22:58.947Z" } ] }
因此,我遇到的問題是它循環得很好,只是無法正確評估助手。
我得到的結果看起來像這樣
cow 2014年12月15日
cow 2014年12月15日
日期總是相同的。
它應該看起來像這樣
cow 2014年12月15日
牛2014年10月15日
我使用this.get('date');
Handlebars.registerHelper('dateFormat', function(context) { if (window.moment) { return moment(this.get('date')).format("MMM Do, YYYY"); }else{ return context; }; });
最初的問題是您沒有在循環的每次迭代中實例化新的Date。
Handlebars.registerHelper('dateFormat', function(context) {
if (window.moment) {
// new Date() !, calling Date("anything") returns current date
return moment(new Date(context)).format("MMM Do, YYYY");
}else{
return context;
};
});
兩個日期均返回了預期結果:
new Date("2014-10-15T14:22:58.947Z")
> Wed Oct 15 2014 09:22:58 GMT-0500 (CDT)
new Date("2014-12-15T14:22:54.088Z")
> Mon Dec 15 2014 08:22:54 GMT-0600 (CST)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.