首页 > 解决方案 > 创建和使用 ejs 辅助函数

问题描述

我正在尝试向我的 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()
},

助手/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 模板中使用它们?

标签: javascriptnode.jsejs

解决方案


您可以在 EJS 模板渲染中使用函数。您的问题很可能是您使用的是流控制标签<%而不是输出标签,<%-或者<%=.

所以你的模板可能应该包含:

<em class="text-muted"><%- timeago(image.timestamp) %></em>

推荐阅读