简体   繁体   中英

Accessing session variable in JADE

My GET /new end point looks like this:

router.get('/new', function(req, res) {
  console.log(JSON.stringify(req.session.application)); //<-- This prints FINE

  res.render('new', { 
    title: 'Add a new intent'
  });
});

And, the new.jade file to be rendered looks like:

...
h1 #{application.name}
...

When I print the req.session.application object on the console, it prints fine, but when the new.jade is rendered, it does not find the application object from the session and thinks it is null . What am I missing?

Provide variable to template

res.render('new', { 
  // <- here is all variables that will be available in jade
  title: 'Add a new intent',
  application: req.session.application
});

I ended up writing a quick midleware function that checks if the application object exists in the session and adds that to the session object like below. With this change, I don't need to pass the req.session.application object to the res.render() method while rendering a Jade view.

Middleware in app.js:

app.use(function(req, res, next) {

  if (req.session && req.session.application) {
    mongoose.model('Application').findOne({ _id: req.session.application._id }, function(err, application) {
      if (application) {
        req.application = application;
        req.session.application = application;  //refresh the session value
        res.locals.application = application;
      }
      // finishing processing the middleware and run the route
      next();
    });
  } else {
    next();
  }
});

Snippet from Jade view:

...
h1 #{application.name}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM