chrisyip / koa-pug

A Pug middleware for Koa

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there an other way to transform the session and flash ?

uinz opened this issue · comments

commented

should I set it in all render function?

likes global locals

ctx.render('sign/signin', {
  session: ctx.session,
  flash: ctx.flash
})
commented

I got it !
#1
add a middleware

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)
        console.log(data)
        await oldRender.call(ctx, tpl, data, options, noCache)
    }

    await next()
})

You don't need to create a new ctx.render, use ctx.state instead:

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

app.use((ctx) => {
  ctx.render('tpl') // session will be available in view automatically
})
commented

thanks much!