Pass variable into view automatically using middleware

Viewed 853

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.

1 Answers
Related