Fabar111
Fabar111

Reputation: 11

How to call an external JavaScript function in a pug file?

DISCLAIMER: I'm really new to pug and express. Sorry if this is obvious, I just can't find an answer anywhere

In the pug file, I'm trying to have a button which calls the function delete() which lives in helperFuncs.js. The delete() function should be run server-side and edit a file (I know the function itself works as intended).

My code is something like this:

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');
    }
};

Whenever I click the button, I get the error Uncaught ReferenceError: helperFuncs is not defined

Please help.

Upvotes: 1

Views: 3290

Answers (1)

tbhaxor
tbhaxor

Reputation: 1943

You need to require the helperFuncs.js in the index.js file and then register the function in the index.js via app.locals.helperFuncs

Your index.js should have

const helperFuncs = require("/path/to/helperFuncs");

// assuming the express app is initialized
app.locals.helperFuncsDelete = helperFuncs.delete

And then in pug file, you can call it

h1= helperFuncsDelete("param1", "param2")

Check out this repository, I have used momentjs in the pug file

Upvotes: 2

Related Questions