Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the session value in ejs

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.)

like image 282
ZMath_lin Avatar asked May 12 '16 10:05

ZMath_lin


1 Answers

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).

like image 101
robertklep Avatar answered Sep 21 '22 20:09

robertklep