始终将变量传递给Express res.render

phi*_*wei 4 node.js express passport.js

Is it possible to always pass certain variables to res.render by default?

More specifically, I'm using the passport middleware that populates req.user with the current user. I need to access this on every page in my site.

It's tedious to supply it each time -- and if I forget, it appears as if the user is not logged in.

Kea*_*eks 5

A simple solution would be to create your own middleware :

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

//...

app.use(passport.initialize());
app.use(passport.session());
//...
app.use(userView);
Run Code Online (Sandbox Code Playgroud)

For each request, This populates a local variable user which is then accessible to the view(s) rendered later in the chain. Activate this middleware after the passport one or req.user will be undefined.