Searching for a way to automatically pass in a value to a view using express on every request.
I'm using this middleware in my startup script, which basically gets an array of stylesheets which I output in the view.
app.use(function(req, res, next) {
req.styles = helper.getStylesForPage(req.originalUrl);
next();
});
I can then use it when rendering the page:
router.get('/', function(req, res, next) {
res.render('index', {
styles: req.styles
});
});
What I'm looking for is a way for this value to automatically be put into this object that's passed into the view, possibly in the middleware function so I don't have to manually do it in every route.
I figured it out, it turns out I can use res.locals
. I just switched my middleware function to:
app.use(function(req, res, next) {
res.locals.styles = helper.getStylesForPage(req.originalUrl);
next();
});
As a sidenote, if you aren't aware what res.locals
is, this object is exposed in your view, and is essentially doing the same thing as this:
router.get('/', function(req, res, next) {
res.render('index', {
styles: helper.getStylesForPage(req.originalUrl)
});
});
The only difference is that it's in a re-usable middleware function, so I don't have to put it on every route now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With