Node.js 在express 3.0中使用mustache.js中的函数
我不熟悉mustache.js,并在node.js的express 3.0中使用它,我想在模板中使用一个helper函数来格式化时间 在app.js中:Node.js 在express 3.0中使用mustache.js中的函数,node.js,express,mustache,Node.js,Express,Mustache,我不熟悉mustache.js,并在node.js的express 3.0中使用它,我想在模板中使用一个helper函数来格式化时间 在app.js中: app.locals({ helper: { friendly_time: require('./libs/util').friendly_time } }); 友好时间是函数函数友好时间(日期){…},日期是日期对象 在index.hjs中: {{#articles}} <div class="org-articl
app.locals({
helper: {
friendly_time: require('./libs/util').friendly_time
}
});
友好时间是函数函数友好时间(日期){…}
,日期是日期
对象
在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> -
<span class="org-article-mtime">
{{#helper.friendly_time}}
{{mtime}}
{{/helper.friendly_time}}
</span>
</li>
</ul>
</div>
{{/articles}}
然后进程抛出错误:
TypeError: Object {{mtime}} has no method 'getFullYear'
我知道
articles[I].mtime
被视为字符串{{mtime}}
,这会导致错误。但我不知道这有多正确。非常感谢您的帮助。我认为您需要使用三个大括号,以便胡须
不会试图清理输入数据。虽然我不确定它对日期对象的作用
{{#helper.friendly_time}}
{{{mtime}}}
{{/helper.friendly_time}}
另一个选项是更新friendlyTime
,这样它也可以在尝试调用getFullYear
之前接受字符串并将其转换为日期对象
function friendly_time(date){
if(!date.getFullYear) {
date = new Date(date);
}
...
}
TypeError:Object{{{mtime}}}没有方法“getFullYear”
错误仍然存在。更新函数不会更正它,因为我传递给函数的是字符串{{{{mtime}}
或{{mtime}}
,而不是它的值(日期对象或字符串对象)!
function friendly_time(date){
if(!date.getFullYear) {
date = new Date(date);
}
...
}