Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Session Variable in Jade View

Im using NodeJS, ExpressJS, PassportJS and Jade.

I have a header menu which will display login or logout. Login is displayed if the user is not yet logged in, and Logout if the user is already logged in.

The menu is in separate jade file: menu.jade and included in the rest of jade files.

include menu

In menu.jade how can I check if the user already logged in? Can I check session variable in jade? Something like below for menu.jade?

if ( req.session.name != null)
    a(href='/logout') Logout
else
    a(href='/login') Login  

Thanks

like image 999
JR Galia Avatar asked Jun 20 '13 01:06

JR Galia


2 Answers

You need to expose session to the templates. The way I do it, is that I put my user variable into locals:

Note: req.user is set by passportJS, you can see their example on it from here (in the bottom)
Note #2: More on locals here

app.get('*', function(req, res, next) {
  // put user into res.locals for easy access from templates
  res.locals.user = req.user || null;

  next();
});

and then in the template you can do this:

- if(_user) {
    div.menuForLoggedInUser
- } else {
    div.menuForLoggedOutUser
- }

If you don't feel like exposing the whole user object to the templates, feel free to just put "loggedIn" to locals and check that... Something like this then:

app.get('*', function(req, res, next) {
  // just use boolean for loggedIn
  res.locals.loggedIn = (req.user) ? true : false;

  next();
});

Edit: Thanks to robertklep for pointing out res.locals vs app.locals

like image 75
Henrik Peinar Avatar answered Nov 14 '22 01:11

Henrik Peinar


I will bring variable that result for check logged in.

// routes/some.js
exports.index = function (req, res) {
    res.render('somepage', {
        isAlreadyLoggedin: checkSessionSomeway()
    })
}

// menu.jade
if ( isAlreadyLoggedin != null)
    a(href='/logout') Logout
else
    a(href='/login') Login
like image 1
yonestra Avatar answered Nov 14 '22 02:11

yonestra