Here’s how to get Nunjucks templates working with Koa’s default router Koa-route.

Assuming you have Koa setup you’ll want to install nunjucks via:

$ npm install nunjucks

Then include Nunjucks in your route. In my case, I have a /routes directory within my project root and so I’m requiring Nunjucks into the index.js that is sitting there.

As well, I’ve written a “render” function that will render the nunjucks template to be served up through the route configured for it via koa-route.

Below is the code snippet showing the above-mentioned scenario.

const nunjucks = require('nunjucks');
const route = require('koa-route');

const render = function (path, params = {}) {
  return new Promise(function(resolve, reject) {
    const env = nunjucks.configure(
      [
        `${__dirname}/../src`, // PATH TO YOUR TEMPLATES
      ],
      {
        autoescape: false,
      },
    );
    resolve(env.render(path));
  });
};


module.exports = [
  route.get('/', async (ctx) => {
    ctx.body = await render(`${__dirname}/../src/pages/home.njc`);
  }),
  route.get('/some_directory', async (ctx) => {
    ctx.body = await render(`${__dirname}/../src/pages/some_directory/index.njc`);
  }),
];

As you can see route.get(‘/server-path-here’ specifies the path that the end user would browse to. As well, I’m using ctx.body to send back the rendered Nunjucks template via the render function which passes in the path to the template that matches the route.