koa-pug 传递 session
 发布于 9 年前  作者 yinzSE  7215 次预览  最后一次回复是 9 年前  来自 分享 

koa-pug 也就是 jade 啦

基本使用方法是

app.use(ctx => {
  ctx.render('tpl', data)
})

但是 像 session 和 flash 这样的数据, 在每一个 render 里面写 真的很烦啊

所以在 new Pug({ app }) 挂载 使 ctx 拥有 render 方法后 并且在调用 ctx.render 方法之前 有时间来改造一下 ctx.render 方法

增加一个中间件

app.use(async (ctx, next) => {
    const oldRender = ctx.render
    const user = ctx.session.user || null
    const flash = ctx.session.flash

    ctx.render = async (tpl, locals, options, noCache) => {
        const data = _.merge({ user, flash }, locals)
        await oldRender.call(ctx, tpl, data, options, noCache)
    }
    await next()
})

比如我这里就给所有的 data 里增加了 userflash 数据

4 回复
yinzSE

额 an other way

app.use(async (ctx, next) => {
    ctx.state = ctx.session
    await next()
})
huangyanxiong01

state是用koa的一个命名空间,和express的locals类似

yinzSE

@huangyanxiong01 是的

ctx.state The recommended namespace for passing information through middleware and to your frontend views.

alsotang

@yinzSEctx.state 不能满足你的需求吗?感觉框架既然已经考虑到这个问题了,直接用就好啊