创建和使用 ejs 辅助函数
Creating and using ejs helper functions
我正在尝试向我的 ejs 模板添加辅助函数。我已遵循 link 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 模板中使用它们?
您可以在EJS 模板渲染中使用函数。您的问题可能是您使用的是流量控制标签 <%
而不是输出标签 <%-
或 <%=
.
因此您的模板可能应该包含:
<em class="text-muted"><%- timeago(image.timestamp) %></em>
我正在尝试向我的 ejs 模板添加辅助函数。我已遵循 link 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 模板中使用它们?
您可以在EJS 模板渲染中使用函数。您的问题可能是您使用的是流量控制标签 <%
而不是输出标签 <%-
或 <%=
.
因此您的模板可能应该包含:
<em class="text-muted"><%- timeago(image.timestamp) %></em>