跳到主要内容
CNode

koa-pug 传递 session

分享
YyinzSE发布于 10 年前最后回复 10 年前
474570

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)

A
alsotang#410 年前
引用 yinzSE@huangyanxiong01 是的 ctx.state The recommended namespace for passing information through middlewa...

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

Y
yinzSE#310 年前
引用 huangyanxiong01state是用koa的一个命名空间,和express的locals类似

@huangyanxiong01 是的

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

H
huangyanxiong01#210 年前

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

Y
yinzSE#110 年前

额 an other way

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

参与回复

登录后即可参与回复。登录