讓koa-hbs模塊支持koa2

我的比較喜歡handlebars渲染,不喜歡ejs、jade之類,所以在試驗koa2開發時,第一時間就想到集成koa-hbs模塊!
koa-hbs模塊來自https://github.com/gilt/koa-hbs
問題是,該模塊不支持koa2,就支持koa1
那麼咱就出動koa-convert模塊來進行轉換……但是,仍然有問題。關鍵點在於ctx.render方法仍然是個generator函數。
這難不倒咱,翻一下koa-convert模塊的源碼,有樣學樣,用下面的辦法解決之:git

const hbs = require('koa-hbs');
const convert = require('koa-convert');
const co = require('co');

app.use(convert(hbs.middleware({
    viewPath: __dirname + '/views',
    partialsPath: __dirname + '/views/partials'
})));
app.use(async (ctx, next) => {
    ctx.render_ = ctx.render;
    ctx.render = function (tpl, locals) {
        return co.call(ctx, ctx.render_(tpl, locals));
    }
    await next();
})

另外,若是不用koa-hbs模塊,而是用支持koa2的koa-views模塊,必須用最新的5.1.2版本(此文章發表時的最新版本),或更高的版本:
npm i koa-views@5.1.2
我在一開始時使用npm i koa-views@next命令安裝,結果不是最新版本,被坑了。github

相關文章
相關標籤/搜索