Create a view engine class first, and implement render and renderString, if the template engine don't support, just throw an error. The view engine is context level, so it receive ctx in constructor.
// lib/view.jsmodule.exports = class MyView { constructor(ctx) { // do some initialize // get the plugin config from `ctx.app.config` } async render(fullpath, locals) { return myengine.render(fullpath, locals); } async renderString() { throw new Error('not implement'); }};
render and renderString support generator function, async function, or normal function return a promise.
If the template engine only support callback, you can wrap it by Promise.
class MyView { render(fullpath, locals) { return new Promise((resolve, reject) => { myengine.render(fullpath, locals, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }};
These methods receive three arguments, renderString will pass tpl as the first argument instead of name in render.
render(name, locals, viewOptions)
name: the file path that can resolve from root (app/view by default)
locals: data used by template
viewOptions: the view options for each render, it can override the view default config in config/config.default.js. Plugin should implement it if it has config.
When you implement view engine, you will receive this options from render, the options contain:
root: egg-view will resolve the name to full path, but seperating root and name in viewOptions.
name: the original name when call render
locals: the original locals when call render
renderString(tpl, locals, viewOptions)
tpl: the template string instead of the file, using in renderString
When render a file, you should specify a extension that let egg-view know whitch engine you want to use. However you can define defaultExtension without write the extension.