Express res.locals.someVariable use in hbs (steering pattern)

I am trying to pass my session variables to my descriptor templates, but I am stuck. Right now I am using this in my app.configure function:

app.use(function(req, res, next){ res.locals.session = req.session; console.log(res.locals.session); next(); }); 

It logs correctly on the console, but when I try to use the "session" variable in my handlebars template, nothing appears. Here is part of my template:

 <body> <nav> {{> topBarPartial}} {{> secondaryBarPartial}} </nav> <div> <p>before</p> {{session}} <p>after</p> {{> mainPartial}} </div> {{> footerPartial}} </body> 

Here is what the console registers:

 { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, userId: 45253262, name: 'Austin' } 

Any ideas?

+6
source share
1 answer

I finally found my solution. Turns out I called it:

 app.use(function(req, res, next){ res.locals.session = req.session; console.log(res.locals.session); next(); }); 

after

 app.use(app.router); 

Actually it should be before app.router, but after

 app.use(express.session({ secret: '***********' })); 
+2
source

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


All Articles