koajs

koa-ejs

示例

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

var app = koa();
render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true,
  locals: locals,
  filters: filters
});

app.use(function *() {
  yield this.render('user');
});

app.listen(7001);

Or you can checkout the example.

设置

  • root: view root directory.
  • layout: global layout file, default is layout, set false to disable layout.
  • viewExt: view file extension, default is html.
  • cache: cache compiled function flag.
  • debug: debug flag.
  • locals: global locals, can be function type, this in the function is koa's ctx.
  • filters: ejs custom filters.
  • open: open flog.
  • close: close floag.

布局

koa-ejs support layout. default layout file is layout, if you want to change default layout file, use settings.layout. Also you can specify layout by options.layout in yield this.render. Also you can set layout = false; to close layout.

<html>
  <head>
    <title>koa ejs</title>
  </head>
  <h3>koa ejs</h3>
  <body>
    <%- body %>
  </body>
</html>

引用

support ejs default include.

<div>
  <% include user.html %>
</div>

过滤

support ejs filters.

<p><%=: users | map : 'name' | join %></p>

you can custom filters pass by `settings.filters'

Locals

pass gobal locals by settings.locals, locals can be functions to get dynamic values. locals also can be generatorFunction or generator, so you can do some async invoke in locals.

var locals = {
  version: '0.0.1',
  now: function () {
    return new Date();
  },
  ip: function *() {  // generatorFunction
    yield wait(10);
    return this.ip; // use this like in koa middleware
  }
};