I have a pug template test.pug that has a button. When clicked, I want the button to call a function that uses parameters passed to the template from the rendering endpoint. Here is the template:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(type="text/javascript").
window.addEventListener('DOMContentLoaded', function(){
document.getElementById('play-button').addEventListener('click', async () => {
console.log(testvar);
console.log('ready');
});
}, false);
body
button(type = 'button' id = 'play-button') Click to play
And here is the endpoint that renders the pug template:
const express = require('express');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('test',{
title:'Player',
testvar:'testvar'
});
});
module.exports = router;
But when I load the page and click the button, I get this error:
Uncaught (in promise) ReferenceError: testvar is not defined
at HTMLButtonElement.<anonymous>
The code works correctly if I comment out console.log(testvar), so I know that the onclick event handler is being added successfully. So apparently the event handler is being added before the parameters are passed to the template.
How can I make the parameters accessible to the onclick event?
Local variables passed through Express's .render() method are only available to Pug and only available while Pug is being compiled on the server. They don't remain available to client-side javascript once Pug has been compiled to HTML and sent to the browser.
If you want them available client-side, you must use Pug interpolation to define the variable within a script tag, alongside your other client-side javascript.
Assuming testvar is a string, you could approach it like this:
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(type="text/javascript").
const testvar = '#{testvar}'; // interpolate the value from Pug
window.addEventListener('DOMContentLoaded', function() {
document.getElementById('play-button').addEventListener('click', async () => {
console.log(testvar);
console.log('ready');
});
}, false);
body
button(type = 'button' id = 'play-button') Click to play
If testvar is an array or object, you'll need to use the JSON.stringify() method to print the array or object into the script tag.