queckezz / koa-views

Template rendering middleware for koa (hbs, swig, pug, anything! :sparkles:)
MIT License
710 stars 87 forks source link

Need koa-views only only a few routes #102

Closed wlingke closed 7 years ago

wlingke commented 7 years ago

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?

int64ago commented 7 years ago

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.

wlingke commented 7 years ago

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

int64ago commented 7 years ago

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

wlingke commented 7 years ago

okay thanks!