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