如何在pug文件中调用外部JavaScript函数?

问题描述 投票:0回答:1

免责声明:我真的是哈巴狗和表情新手。抱歉,如果这很明显,我什么地方都找不到答案

在哈巴狗文件中,我试图有一个按钮,该按钮调用位于helperFuncs.js中的函数delete()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
    });
})

index.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

请帮助。

javascript pug
1个回答
0
投票
const helperFuncs = require("/path/to/helperFuncs"); // assuming the express app is initialized app.locals.helperFuncsDelete = helperFuncs.delete
© www.soinside.com 2019 - 2024. All rights reserved.