【问题标题】:Mustache doesn't Evaluate {{}} inside functionMustache 不评估函数内部的 {{}}
【发布时间】:2013-06-15 04:45:32
【问题描述】:

我正在尝试使用带有 mustache 的 moment.js 格式化 JS Date () 对象,但是 mustache 不会将评估值传递给函数。

在主干视图中:

render: function () {
    var user = this.user.toJSON ();  //model

    _.extend (user, {formatLastLoginAt: this.formatLastLoginAt});

    var rendered = mustache.render (template, user);
    this.$el.html (rendered);

    return this;
},

formatLastLoginAt: function () {
   return function (lastLoginAt) {
     return moment (lastLoginAt).format ('Do MMMM YYYY');
  }
}

用户对象绑定:

在模板中:

{{#lastLoginAt}}
    <tr>
     <td>Last Login:</td> 
     <td>{{#formatLastLoginAt}}{{lastLoginAt}}{{/formatLastLoginAt}}</td>
    </tr>
{{/lastLoginAt}}

moment.js 给出 NaN 错误,因为 'lastLoginAt' 作为文字字符串“{{lastLoginAt}}”而不是其 Date () 值传入。

尝试使用moment ().format (),它可以工作。因此 lambda 构造应该没问题,{{#lastLoginAt}} 是非空的。

我错过了什么?感谢您的建议。谢谢。

【问题讨论】:

  • Lambda 没有被赋予原始值。但是,它们可以为您提供内部部分的渲染,您可以对其进行解析以重建原始值...根本不实用,但这是您使用此工具可以做到的最好的事情。其他一些 Mustache 实现,在其他语言中,更方便,并且支持 lambda 构造(例如,github.com/groue/GRMustache/blob/master/Guides/…

标签: mustache momentjs


【解决方案1】:

Mustache 不会为您呈现内容。你的函数接受一个参数,lastLoginAt,但 Mustache 会传递给你另一个参数:render。用lastLoginAt 调用render 将扩展变量:

formatLastLoginAt: function () {
   return function (lastLoginAt, render) {
     lastLoginAt = render(lastLoginAt);  // expand variable
     return moment (lastLoginAt).format ('Do MMMM YYYY');
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2015-12-01
    • 2017-04-06
    • 1970-01-01
    • 2014-09-14
    相关资源
    最近更新 更多