【问题标题】:Handlebars.js helper in #each loop returns same results?#each 循环中的 Handlebars.js 助手返回相同的结果?
【发布时间】:2014-12-16 04:25:17
【问题描述】:

我正在尝试使用 #each 循环内的车把注册的 momentjs 助手来格式化我的日期。注册的助手看起来像这样:

Handlebars.registerHelper('dateFormat', function(context) { 如果(window.moment){ return moment(Date(context)).format("MMM Do, YYYY"); }别的{ 返回上下文; }; });

车把循环如下所示

{{#每个控制器}}
{{{正文}}}
{{{dateFormat 日期}}}
{{/每个}}

正在循环的 JSON 在此

{ “主意”:[ { "_id":"548eeebeda11ffbe12000002", “身体”:“牛”, “标签”:“牛”, “日期”:“2014-12-15T14:22:54.088Z” }, { "_id":"548eeec2da11ffbe12000003", “身体”:“牛”, “标签”:“驼鹿”, “日期”:“2014-10-15T14:22:58.947Z” } ] }

所以我遇到的问题是它循环得很好,只是没有正确评估助手。

我得到的结果如下所示

牛 2014 年 12 月 15 日
牛 2014 年 12 月 15 日
日期始终相同。

它应该是这样的
牛 2014 年 12 月 15 日
牛 2014 年 10 月 15 日

【问题讨论】:

    标签: javascript ember.js handlebars.js handlebarshelper


    【解决方案1】:

    我使用 this.get('date'); 让它工作了

    Handlebars.registerHelper('dateFormat', function(context) { 如果(window.moment){ return moment(this.get('date')).format("MMM Do, YYYY"); }别的{ 返回上下文; }; });

    【讨论】:

      【解决方案2】:

      最初的问题是您没有在循环的每次迭代中实例化一个新的 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)
      

      【讨论】:

        猜你喜欢
        • 2022-07-21
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 2019-04-28
        • 2016-07-22
        • 2017-03-10
        • 1970-01-01
        相关资源
        最近更新 更多