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