Skip to content

strawbrary/koa-nunjucks-2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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](#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

About

Lightweight Koa middleware for Nunjucks

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •