javascript - 如何在 pug 文件中调用外部 JavaScript 函数?
问题描述
免责声明:我对哈巴狗和表达真的很陌生。抱歉,如果这很明显,我只是无法在任何地方找到答案
在 pug 文件中,我试图有一个按钮来调用delete()
位于 helperFuncs.js 中的函数。该delete()
函数应该在服务器端运行并编辑一个文件(我知道该函数本身按预期工作)。
我的代码是这样的:
index.js:
const helperFuncs = require('./lib/helperFuncs');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(cors());
app.get('/', function(req, res) {
let posts = helperFuncs.getAllPosts();
res.render('index', {
posts,
helperFuncs
});
})
指数.pug:
doctype html
style
include ./style.css
html
head
title MyApp
body
h1 History
.posts-container
each post, index in posts
.post(item=post, index=index)
button(type='button' onclick='helperFuncs.delete(post.id)')
p.text #{post.text}
helperFuncs.js:
module.exports = {
delete: function(id) {
console.log('Deleting a post...')
let newHistory = history.filter(obj => {
return obj.id !== id;
})
fs.writeFileSync('./server/data/history.json', JSON.stringify(newHistory), 'utf8');
}
};
每当我单击按钮时,我都会收到错误消息Uncaught ReferenceError: helperFuncs is not defined
请帮忙。
解决方案
您需要在 index.js 文件中要求 helperFuncs.js,然后通过在 index.js 中注册该函数app.locals.helperFuncs
你的 index.js 应该有
const helperFuncs = require("/path/to/helperFuncs");
// assuming the express app is initialized
app.locals.helperFuncsDelete = helperFuncs.delete
然后在 pug 文件中,你可以调用它
h1= helperFuncsDelete("param1", "param2")
查看这个存储库,我在 pug 文件中使用了 momentjs
推荐阅读
- html - Extract date from text inside html tags using XPATH
- tableau-api - 查找两个给定日期之间每个月的天数
- azure - 如何通过“完整”模式部署到 Azure 来忽略锁定的资源?
- c# - 如何获得所有可能的正则表达式匹配
- java - 继续接收 javax.mail.Session$1: 方法
()V 尝试使用 Springboot + mvc 发送电子邮件时未找到 - apache-kafka-streams - 使用变更日志会导致应用程序本身出现瓶颈吗?
- c# - 如何在 ASP.NET MVC Core 2.2 中使用 @Url.Action 传递文本框值
- gitlab - 使用流覆盖率报告获取 Gitlab CI 覆盖率
- sql-server - SSRS - 如何使用来自不同数据集的值作为图表中的 X 轴
- android - 为什么从 EditText 中选择一个长字并覆盖到下一行时,布局会消失并重新出现?