Checking a Session Variable in Jade View

I use NodeJS, ExpressJS, PassportJS and Jade.

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

The menu is in a separate jade file: menu.jade and is included in other jade files.

 include menu 

In menu.jade, how can I check if a user has already been registered? Can I check the jade session variable? Something like below for menu.jade ?

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

thanks

+4
source share
2 answers

You need to open a session for templates. The way I do this is that I put my user variable in local:

Note: req.user is defined by a JS passport, you can see their example from here (below)
Note # 2: More about local 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 want to expose the entire user object to templates, feel free to just put "loggedIn" in locals and check that ... Something like this:

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

Edit: Thanks robertklep for specifying res.locals vs app.locals

+7
source

I will give a variable which will be received for check.

 // 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 
+1
source

Source: https://habr.com/ru/post/1487182/


All Articles