2

I am trying to format JS Date () object with moment.js with mustache, however mustache doesn't pass evaluated value to function.

In backbone view:

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');
  }
}

user object binding: user object before pass to mustache

In template:

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

moment.js gives NaN error as 'lastLoginAt' pass in as literal string "{{lastLoginAt}}" rather than its Date () value.

Tried with moment ().format (), it works. Thus the lambda construct should be ok and {{#lastLoginAt}} is non-empty.

Anything I missed out? Appreciate your advice. Thank you.

4

1 回答 1

4

Mustache won't render the contents for you. Your function takes one argument, lastLoginAt, but Mustache will pass you another: render. Calling render with lastLoginAt will expand the variable:

formatLastLoginAt: function () {
   return function (lastLoginAt, render) {
     lastLoginAt = render(lastLoginAt);  // expand variable
     return moment (lastLoginAt).format ('Do MMMM YYYY');
  }
}
于 2013-06-15T05:14:46.357 回答