koa-pug 传递 session
发布于 8 年前 作者 yinzSE 5902 次浏览 来自 分享

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 回复

额 an other way

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

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

@huangyanxiong01 是的

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

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

回到顶部