-->

Mustache doesn't Evaluate {{}} inside function

2020-07-26 17:24发布

问题:

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:

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.

回答1:

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