【问题标题】:Using functions in mustache.js in express 3.0在 express 3.0 中使用 mustache.js 中的函数
【发布时间】:2012-10-08 20:01:15
【问题描述】:

我是 mustache.js 的新手,在 node.js 的 express 3.0 中使用它,我想使用辅助函数来格式化模板中的时间。

在 app.js 中:

app.locals({
  helper: {
    friendly_time: require('./libs/util').friendly_time
  }
});

friendly_time 是一个函数function friendly_time(date){ ... },日期是一个Date 对象。

在 index.hjs 中:

{{#articles}}
  <div class="org-articles">
    <ul class="org-articles-list">
      <li class="org-articles-item">
        <a class ="org-article-title" href="/o/{{title}}">
        {{title}}
        </a>&nbsp;-&nbsp;
        <span class="org-article-mtime">
          {{#helper.friendly_time}}
            {{mtime}}
          {{/helper.friendly_time}}
        </span>
      </li>
    </ul>
  </div>
{{/articles}}

articles 是一个包含如下对象的数组:

{
    title: 'title',                           // a string
    mtime: new Date() // a js Date object
}

然后进程抛出错误:

TypeError: Object {{mtime}} has no method 'getFullYear'

我知道articles[i].mtime 被视为字符串{{mtime}},这会导致错误。但我不知道这有多正确。任何帮助表示赞赏。

【问题讨论】:

    标签: node.js express mustache


    【解决方案1】:

    我认为您需要使用三个大括号,以便mustache 不会尝试清理输入数据。虽然我不肯定它对 Date 对象的作用。

    {{#helper.friendly_time}}
        {{{mtime}}}
    {{/helper.friendly_time}}
    

    另一种选择是更新friendlyTime,使其也可以接受字符串并将其转换为日期对象,然后再尝试调用getFullYear

    function friendly_time(date){
        if(!date.getFullYear) {
            date = new Date(date);
        }
    
        ...
    }
    

    【讨论】:

    • TypeError: Object {{{mtime}}} has no method 'getFullYear' 错误依然存在。更新函数不会更正它,因为我传递给函数的是字符串{{{mtime}}}{{mtime}},而不是它的值(日期对象或字符串对象)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2010-10-02
    相关资源
    最近更新 更多