Adam Magaluk
Adam Magaluk

Reputation: 1726

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});

Upvotes: 25

Views: 8678

Answers (2)

Adam Magaluk
Adam Magaluk

Reputation: 1726

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>

Upvotes: 11

josh3736
josh3736

Reputation: 144912

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();
});

Upvotes: 35

Related Questions