koa本身并没有针对模板引擎做任何工作,在koa的源码里也仅仅只有初始化context.state = {};的一行代码
如果不引入其他依赖的话可以自己写一个:
function myRender(dir, opts) {
return function* (next) {
this.render = (filename, locals) => {
this.body = jade.compileFile(path.join(dir, filename) + '.jade', opts)(locals);
};
yield next;
}
};
如果你用了co-render这样的模块的话可以这么写:
const render = require('co-render');
function myRender(dir, opts) {
opts = _extend({
engine: 'jade'
}, opts);
return function* (next) {
this.render = function* (filename, locals) {
this.body = yield render(path.join(dir, filename) + '.jade', _extend(opts, locals));
};
yield next;
}
};
我这是koa1的写法,你可以在opts上挂载全局的locals对象
可以用中间件的形式使用app.use(myRender('path/to/views', locals))