queckezz/koa-views

Need koa-views only only a few routes

wlingke opened this issue · 4 comments

Suppose I have a bunch of routes - /a, /b, /c, /d, /e, /f, /g ..., but only routes /a and /b will ever render any pages.

Is it better to call app.use(views(..)) at the top of my server (before any routes are defined) OR is it better to call app.use('/a', mount(views(...))) - ie only at the top of the routes that need it?

Does this work for you ?

app.use(async (ctx, next) => {
  if (shouldRender(ctx.path)) {
     await ctx.render();
  } else {
    await next();
  }
})

Here shouldRender is your route rules.

Yea I was planning to ctx.render based on route anyways, but I was wondering if it was better to load the app.use(views) only on routes that needed it

You can directly render specific route by

app.use('/a', async ctx => {
  await ctx.render();
})

koa-views only provides a .render method on ctx, it doesn't break any route, please set routes according to requirements

okay thanks!