0

I have this in app.js...

    var koa = require('koa');
    var locals = require('koa-locals');
    var jade = require('koa-jade');

    var app = koa();

    locals(app, {
        moment: require('moment'),
        _: require('lodash')
    });

    app.use(jade.middleware({
       viewPath: __dirname + '/views',
       debug: true,
       pretty: true,
       compileDebug: false,
       locals: this.locals
   }));

And you've guessed it, moment is undefined in a view.

What am I missing? And incidentally why does the documentation for koa-local have the weird require in the example...

var locals = require('../'); 
Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • Try debugging what the value of `this.locals` is inside of your second middleware (the jade middleware). Also, the module seems to debug on this channel `koa:locals`, so can you see any issues when running your node command with `DEBUG=koa:locals node --harmony app.js` ? This module uses a less-than-ideal way of delegating the `.locals` accessor on `app.ctx` and `ctx.request` to the `app.locals` and something could be getting snagged there depending on what jade does with the `locals` option. – jbielick Mar 01 '15 at 20:35

2 Answers2

0

Really i never used koa-locals, but currently you can use built in feature of koa state to pass data to your view.

this.state.utils = {
    moment: require('moment'),
    _: require('lodash')
};
Gonzalo Bahamondez
  • 1,371
  • 1
  • 16
  • 37
0

At the time you're calling app.use(jade.middleware({, this.locals refers to the global object. You're not inside of a middleware closure, you're just using this (global) and locals (expectedly) has never been defined on the global object.

Maybe just pass the same object that you're giving to koa-locals to jade.middleware?

var koa = require('koa');
var locals = require('koa-locals');
var jade = require('koa-jade');

var app = koa();
var helpers = {
  moment: require('moment'),
  _: require('lodash')
};

locals(app, helpers);

app.use(jade.middleware({
   viewPath: __dirname + '/views',
   debug: true,
   pretty: true,
   compileDebug: false,
   locals: helpers
}));
jbielick
  • 2,800
  • 17
  • 28