Lightweight Koa middleware for Nunjucks.
npm install --save koa-nunjucks-2
NOTE: v3 requires Koa 2 or later. If you're using Koa 1, use v2 of this package.
const Koa = require('koa');
const app = new Koa();
const koaNunjucks = require('koa-nunjucks-2');
const path = require('path');
app.use(koaNunjucks({
ext: 'html',
path: path.join(__dirname, 'views'),
nunjucksConfig: {
trimBlocks: true
}
}));
app.use(async (ctx) => {
await ctx.render('home', {double: 'rainbow'});
});
- ext (default: 'njk'): Extension that will be automatically appended to the file name in
ctx.render
calls. Set to a falsy value to disable. - path (default: current directory): Path to the templates. Also supports passing an array of paths.
- writeResponse (default: true): If true, writes the rendered output to
response.body
. - functionName (default: 'render'): The name of the function that will be called to render the template.
- nunjucksConfig: Object of Nunjucks config options.
- configureEnvironment: A function to modify the Nunjucks environment. See the [Extending Nunjucks](#Extending Nunjucks) section below for usage.
Use ctx.state to make a variable available in all templates.
Use the configureEnvironment
config option to define a function which will receive a Nunjucks Environment as its argument. This allows you to define custom filters, extensions etc.
app.use(koaNunjucks({
ext: 'html',
path: path.join(__dirname, 'views'),
configureEnvironment: (env) => {
env.addFilter('shorten', (str, count) => {
return str.slice(0, count || 5);
});
}
}));