Reputation: 15686
Once a user has been logged in, how do I reference this.req.user
from inside of a view?
I think this would involve updating the locals collection of the Jade middleware. I haven't been able to get a reference to this object though.
Up until now I've been doing the following...
app.use(jade.middleware({
viewPath: __dirname + '/views',
debug: true,
pretty: true,
compileDebug: true,
locals: {
moment: require('moment'),
_: require('lodash')
}
}));
And then in the view there'd be something like this...
span=moment(new Date(item.date)).calendar()
Of course now I have a user object that cannot be assigned at set-up.
Upvotes: 0
Views: 630
Reputation: 1901
There are a few libraries you could use, here is how you would do it with co-views:
'use strict';
let koa = require('koa'),
views = require('co-views');
let app = koa();
let render = views(__dirname + '/jade/', {default: 'jade'});
app.use(function *controller(){
let data;
data = {
user: this.req.user
};
this.body = yield render('jadeFileName', data);
});
I made a screencast on serving content from Koa with Jade which might be helpful. You can find it at:
http://knowthen.com/episode-6-serving-content-in-koajs-with-jade/
EDIT:
Here is an option in response to your desire to not pass the user when calling render.
'use strict';
let koa = require('koa'),
views = require('co-views');
let app = koa();
let render = views(__dirname + '/jade/', {default: 'jade'});
// using custom middleware
app.use(function *(next){
this.render = function (fileName, data){
data = data || {};
data.user = this.req.user;
return render(fileName, data);
}
yield next;
});
app.use(function *controller(){
this.body = yield this.render('jadeFileName');
});
Upvotes: 1
Reputation: 11677
In your express configuration, you need to store the user object in res.locals after you authenticate the user, something like this works:
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
Then you should be able to reference the user in your jade templates:
block content
p= user.email
Upvotes: 0