lets say I'd defined a variable inside my app, and I wanted to use that variable in my Pug template. Is it possible for Pug to access this variable if I don't pass it through in the render statement?
I have a variable whose value will periodically change that should be visible on almost every page of my website. Every page it should be visible from will extend the same template, so if I could somehow access the variable from inside that template I only need to write code in one place. I know that I can include the variable inside the locals
portion of res.render('template', { ... })
but this doesn't seem like a practical solution given I could add new routes in future. Does anybody have any idea how I could achieve this in the neatest and most readable way?
CodePudding user response:
I found an answer here by tbhaxor, posting in case anybody stumbles onto this in future.
Define your variables/functions inside some helper.js
file and export them. Then require that file in your index.js
file e.g. const helper = require('./helper.js`);
so you can now use:
app.locals.SOME_NAME = helper.someFunctionOrVariable
Which can be accessed within your template by calling - const result = SOME_NAME();
Hopefully this helps anybody else, all credit to tbhaxor.