javascript - 创建和使用 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 模板中使用它们?
解决方案
您可以在 EJS 模板渲染中使用函数。您的问题很可能是您使用的是流控制标签<%
而不是输出标签,<%-
或者<%=
.
所以你的模板可能应该包含:
<em class="text-muted"><%- timeago(image.timestamp) %></em>
推荐阅读
- r - 为什么线图没有跟随 ggplot 中的第二个 y 轴?
- android - 滚动结束后使底部按钮出现
- mediawiki - 将 Url 的查询结果格式化为 Semantic MediaWiki 中的给定字符串
- javascript - 减少多个 if 语句的最佳方法是什么?
- sql - 将 Pandas Dataframe 输出从 NoneType 替换为 0
- javascript - 我只想将博客链接的开头重定向到另一个网站
- python - 从 __init__ 分配属性的快捷方式
- c# - 如何等待事件处理程序调用?
- computation-theory - 上下文无关语言是否是确定性上下文无关语言
- c++ - 将 Conan Include 链接到 VS Code