I am making a login module using session(using express and nodes). When the user has logged in, I save the user in the session.
req.session.user= ...
How can I get the session value in a .ejs view like:
<label>
您好!<%= req.session.user.username %>
</label>
But this doesn't work.
I can do it by this:
router.get('/home',function(req, res){
var val = req.session.user;
res.render('home',{user:val});
});
.ejs:
<p>
您好!<%= user.username %>
</p>
But this is so troublesome. What is the better way to do it?
(In php, I can just use $_SESSION to get the value in a view file.)
You can use res.locals
to expose particular data to all templates.
In your situation, you could add the following middleware to Express:
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
This will make a user
variable available in all your templates.
You do need to make sure that you add that middleware after req.session
has been set (which is usually after express-session
has been added to the middleware chain).
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