Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable into view automatically using middleware

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.

like image 369
ncf Avatar asked Mar 23 '16 05:03

ncf


1 Answers

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.

like image 54
ncf Avatar answered Nov 03 '22 00:11

ncf