T94j0
T94j0

Reputation: 87

Streamlining workflow of Express and Jade

I am currently working on a project that uses MongoDB, Express, and Jade. We always want to throw the user account JSON data into the view. Every single controller we have, we are writing

exports.theView = function(req, res){
    User.findOne({ username: req.user.username }, function(err, user){
        res.render('theview.jade', { user: user });
    });
}

There seems like there should be a better, more efficient way of doing this.

Any suggestions?

Upvotes: 0

Views: 34

Answers (1)

Bartosz Czerwonka
Bartosz Czerwonka

Reputation: 1651

I think you can use middleware to set response locals (http://expressjs.com/api.html#res.locals) to set user to view every reqeust.

Middleware:

app.use(function(req, res, next) {
  User.findOne({ username: req.user.username }, function(err, user){
         res.locals.user = req.user;
         next()
    });
});

Route:

app.get('/', function(req, res, next) {
   res.render('theview.jade', {title: 'Title'});  
});

View:

block content
  h1= title
  p= user.name

Upvotes: 1

Related Questions