JSPM

  • Created
  • Published
  • Downloads 20491
  • Score
    100M100P100Q27230F
  • License MIT

Template rendering middleware for koa

Package Exports

  • koa-views

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (koa-views) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

koa-views

Build status NPM version NPM downloads Dependency Status License

Template rendering middleware for koa.

Note: This master branch is for koa's upcoming version koa@2. Take a look at the v1.x branch for koa@1.

Installation

$ npm install koa-views@next

Templating engines

koa-views is using consolidate under the hood.

List of supported engines

Example

var views = require('koa-views');

// Must be used before any router is used
app.use(views(__dirname + '/views', {
  map: {
    html: 'underscore'
  }
}));

app.use(async function (ctx, next) {
  ctx.state = {
    session: this.session,
    title: 'app'
  };

  await ctx.render('user', {
    user: 'John'
  });
});

For more examples you can take a look at the tests.

API

views(root, opts)

  • root: Where your views are located. Must be an absolute path. All rendered views must be relative to this path
  • opts (optional)
  • opts.extension: Default extension for your views

Instead of providing the full file extension you can omit it.

app.use(async function (ctx) {
  await ctx.render('user.jade')
})

vs.

app.use(views(__dirname, { extension: 'jade' }))

app.use(async function (ctx) {
  await ctx.render('user')
})
  • opts.map: Map a file extension to an engine

In this example, each file ending with .html will get rendered using the nunjucks templating engine.

app.use(views(__dirname, { map: {html: 'nunjucks' }}))

// render `user.html` with nunjucks
app.use(async function (ctx) {
  await ctx.render('user.html')
})

Debug

Set the DEBUG environment variable to koa-views when starting your server.

$ DEBUG=koa-views

License

MIT