Reputation: 87
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
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