Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express3 - Middleware to add render data to all render requests

Is it possible through express middleware or another method to add render data (the second option in res.render) to each call in the apps routes.

My app is using passport for authentication and I would like a middleware to always append the user information to each rendered template.

Currently each of my calls to res.render look similar to. I would like to remove the user : req.user and add that to a middleware function.

// Page 1
res.render("somepage1",{data : "somepage1", user : req.user});

// Page 2
res.render("somepage2",{data : "somepage2", user : req.user});
like image 813
Adam Magaluk Avatar asked Feb 24 '13 23:02

Adam Magaluk


2 Answers

Express does provide app.locals and res.locals, which it automatically merges with explicit locals passed in to render by a route handler.

app.use(function(req, res, next) {
    res.locals.user = req.user;
    next();
});

Alternatively, you could hot patch the render function. I'd avoid this since it's extra overhead, but if for some reason you needed to pass information not available before your route handler runs, it's an option:

app.use(function(req, res, next) {
    var render = res.render;
    res.render = function(view, locals, cb) {
        if (typeof locals == 'object') locals.user = req.user;
        render.call(res, view, locals, cb);
    };
    next();
});
like image 111
josh3736 Avatar answered Nov 11 '22 13:11

josh3736


Figured it out.

You can use locals in your middleware.

  app.use(function(req, res, next){
    res.locals.user = req.user;
    next();
  });

Then in the templates use.

<h1>User Name:{{user.name}}</h1>

<h1>User Name:{{_locals.user.name}}</h1>

like image 44
Adam Magaluk Avatar answered Nov 11 '22 14:11

Adam Magaluk