包详细信息

koa-views

queckezz87.7kMIT不推荐使用8.1.0

This package is deprecated, please use the new fork @ladjs/koa-views. Maintenance is supported by Forward Email at https://forwardemail.net ; follow/watch https://github.com/ladjs/koa-views for updates and release changelog

Template rendering middleware for koa

koa, render, views, app-wide

自述文件

koa-views

koa-views NPM version NPM downloads Dependency Status License

Template rendering middleware for koa@2.

Installation

npm install koa-views

Templating engines

koa-views is using @ladjs/consolidate under the hood.

List of supported engines

NOTE: you must still install the engines you wish to use, add them to your package.json dependencies.

Example

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

const render = views(__dirname + '/views', {
  map: {
    html: 'underscore'
  }
})

// Must be used before any router is used
app.use(render)
// OR Expand by app.context
// No order restrictions
// app.context.render = render()

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

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

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

Simple middleware

If you need to simply render pages with locals, you can install koa-views-render:

npm install koa-views-render

Then simply use it on your routes and its arguments will be passed to ctx.render.

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

// ...

app.use(render('home', { title : 'Home Page' }));

API

views(root, opts)

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

  • opts.autoRender: Whether to use ctx.body to receive the rendered template string. Defaults to true.

const render = views(__dirname, { autoRender: false, extension: 'pug' });
app.use(render)
// OR
// app.context.render = render()

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

vs.

const render = views(__dirname, { extension: 'pug' })
app.use(render)
// OR
// app.context.render = render()

app.use(async function (ctx) {
  await ctx.render('user.pug')
})
  • 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.pug')
})

vs.

const render = views(__dirname, { extension: 'pug' })
app.use(render)
// OR
// app.context.render = render()

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.

const render = views(__dirname, { map: {html: 'nunjucks' }})
app.use(render)
// OR
// app.context.render = render()
// render `user.html` with nunjucks
app.use(async function (ctx) {
  await ctx.render('user.html')
})
  • opts.engineSource: replace @ladjs/consolidate as default engine source

If you’re not happy with @ladjs/consolidate or want more control over the engines, you can override it with this options. engineSource should be an object that maps an extension to a function that receives a path and options and returns a promise. In this example templates with the foo extension will always return bar.

const render = views(__dirname, { engineSource: {foo: () => Promise.resolve('bar')}})
app.use(render)
// OR
// app.context.render = render()

app.use(async function (ctx) {
  await ctx.render('index.foo')
})
  • opts.options: These options will get passed to the view engine. This is the time to add partials and helpers etc.
const app = new Koa()
  .use(views(__dirname, {
    map: { hbs: 'handlebars' },
    options: {
      helpers: {
        uppercase: (str) => str.toUpperCase()
      },

      partials: {
        subTitle: './my-partial' // requires ./my-partial.hbs
      },

      cache: true // cache the template string or not
    }
  }))
  .use(function (ctx) {
    ctx.state = { title: 'my title', author: 'queckezz' }
    return ctx.render('./my-view.hbs')
  })

Debug

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

$ DEBUG=koa-views

License

MIT

更新日志

5.0.0~6.0.0

  • koa@2 is supported by default and koa@1 is not supported
  • don't compile released code to ES5 (this means you need Node_v7.6, the same as koa@2 requires)
  • [BugFix] fix error if filename contains dot
  • [BugFix] default extension should not be changed
  • [BugFix] fix partials not working properly in handlebars
  • make consolidate engine source optional and allow configuration

5.0.0

  • koa@2 support by @ifraixedes

4.1.0

  • [BugFix] state will pass now if no locals are passed

4.0.1

  • [Bugfix] Select correct extension in order to decide if the view should be sent or rendered

4.0.0

Breaking changes

  • no root option -> use views(path, ...)
  • path should now always be absolute (no magic anymore)
// don't
app.use(views('./views'))

// do
app.use(views(__dirname + '/views'))
  • opts is now always an object, no string can be passed in as engine
// this
app.use(views(__dirname + '/views', 'jade'))
// is now this
app.use(views(__dirname + '/views', {
  extension: 'jade'
}))
  • opts.default renamed to opts.extension to avoid misconceptions

Non-breaking changes

  • more robust file require
// all valid (when opts.extension) set
./fixtures/index.ejs
./fixtures/index.ejs
./fixtures/index
./fixtures/
./fixtures
fixtures

3.0.0

  • Breaking: this.locals is now this.state
  • return and yield next if this.render already exists

2.1.2

  • support default to ./index.[ext]

2.0.3

  • Resolves circular dependencies in this.locals

2.0.0 / 4.28.2014

  • default extension to .html
  • better debug messages
  • move default ext to options
  • name middleware
  • change locals behavior so they don't get set twice
  • fix path confusion, hopefully.

1.2.0 / 2.22.2014

  • use middleware instead of direct app reference
  • this.body = yield this.render() -> yield this.render()

1.1.0 / 2.16.2014

  • Use a koa instance to extend koa itself instead of adding a each method on every request.
  • this.locals = instead of this.locals()

1.0.0 / 2.15.2014

  • Renamed project from koa-render to koa-views.
  • added this.locals() for per-request locals.
  • refactored API
  • more descriptive debug messages.

0.1.0 / 12.19.2013

  • Allowing using extension different than engine's shortname.

0.0.1 / 12.19.2013

  • Initial commit.