0

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.

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189

2 Answers2

1

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');
});
James Moore
  • 1,881
  • 14
  • 18
  • But then I need to pass the user with every render. – Ian Warburton Jan 26 '15 at 01:05
  • Good idea. I've updated your answer because it didn't quite work. – Ian Warburton Jan 26 '15 at 14:18
  • Namely... a reference needed to be saved for the default render and the default render needed to be called on 'this'. The new version needed the correct signature and needed to be a generator. Also I added in the check for IsAuthenticated because I was already doing that. Seems like a good idea to do both in one custom middleware. – Ian Warburton Jan 26 '15 at 14:27
0

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
Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33