node.jspugpassport.jskoakoa-passport

How do I access the logged in user object in a view?


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.


Solution

  • 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');
    });