Ready to take your JavaScript development to the next level? Meet npm Enterprise - the ultimate in enterprise JavaScript. Learn more »

koa-nunjucks-2

3.0.2 • Public • Published

koa-nunjucks-2

Lightweight Koa middleware for Nunjucks.

NPM version Build status License Dependency status

Installation

npm install --save koa-nunjucks-2

NOTE: v3 requires Koa 2 or later. If you're using Koa 1, use v2 of this package.

Usage

Example

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'});
});

Config Options

  • 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 section below for usage.

Global Template Variables

Use ctx.state to make a variable available in all templates.

Extending Nunjucks

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);
    });
  }
}));
 

License

MIT

install

npm i koa-nunjucks-2

Downloadsweekly downloads

201

version

3.0.2

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability