![](/img/trans.png)
[英]How return the result of a function from an external javascript script to a pug file?
[英]How to call an external JavaScript function in a pug file?
免责声明:我对哈巴狗和快递真的很陌生。 对不起,如果这很明显,我在任何地方都找不到答案
在 pug 文件中,我试图有一个按钮调用位于 helperFuncs.js 中的函数delete()
。 delete()
函数应该在服务器端运行并编辑文件(我知道函数本身按预期工作)。
我的代码是这样的:
索引.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 文件中 require helperFuncs.js,然后通过app.locals.helperFuncs
在 index.js 中注册该函数
你的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.