首页 > 解决方案 > 如何在 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

请帮忙。

标签: javascriptpug

解决方案


您需要在 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


推荐阅读