【发布时间】:2020-10-21 08:19:02
【问题描述】:
我正在尝试向我的 ejs 模板添加辅助函数。我已按照链接nodejs ejs helper functions 中提供的答案进行操作。但是,它似乎不起作用。 ViewModel 对象中的所有其他属性都会出现,但时间戳属性除外,该属性被传递给app.locals 中的时间戳函数。
正在渲染到主模板的对象
const ViewModel = {
image:{
uniqueId: 1,
title: 'Sample Image 1',
description: 'This is a sample.',
filename: 'sample1.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
},
helpers/timeago.js
const moment = require('moment');
module.exports = (timestamp) => {
return moment(timestamp).startOf('minute').fromNow();
}
来自 server.js 的相关代码
const helpers = require('./helpers');
helpers(app);
helper.js 将函数放入 app.locals
const timeago = require('./../helpers/timeago');
module.exports = (app) => {
app.locals.timeago = timeago;
};
Main.ejs 模板:使用 app.locals 中的函数
<em class="text-muted"><% timeago(image.timestamp) %></em>
如何成功地将函数添加到 app.locals 并在 ejs 模板中使用?
【问题讨论】:
标签: javascript node.js ejs