I am looking to implement a clickable button in PugJS that triggers JavaScript code within Node.js.
views/index.pug
doctype html
html
head
title #{title}
link(rel='stylesheet', href='/css/style.css')
meta(name="viewport" content="width=device-width, initial-scale=1")
body
main
block header
header.header
h1 #{title}
block content
button(type='submit' onClick='foo();') Click
index.js
var http = require('http'),
fs = require('fs'),
util = require('util'),
express = require('express'),
pug = require('pug');
var app = express();
app.set('view engine', 'pug');
var foo = function() {
console.log("foobar");
};
app.get('/', (req, res) => {
res.render('index', {title: "Awesome name", func: foo});
});
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
// sending a response does not pause the function
foo();
});
app.use(express.static(__dirname + '/public'));
const server = app.listen(7000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Directly referencing `foo` results in "undefined" as the function is undefined in scope. Attempting to reference `func` with `#{func}` inside index.pug leads to errors. How can I correctly reference the JavaScript function within Node.js from a button created in PugJS?