Mustache doesn't Evaluate {{}} inside function

霸气de小男生 提交于 2019-12-09 21:20:27

问题


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


来源:https://stackoverflow.com/questions/17120261/mustache-doesnt-evaluate-inside-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!