title: View Template Rendering

In most cases, we need to fetch data and render with template files.
So we need to use corresponding view engines.

egg-view is a built-in plugin to support using multiple view engines in one application.
All view engines are imported as plugins.
With egg-view developers can use the same API interface to work with different view engines.
See View Plugin for more details.

Take the officially supported View plugin egg-view-nunjucks as an example:

Install view engine plugin

  1. $ npm i egg-view-nunjucks --save

Enable view engine plugin

  1. // config/plugin.js
  2. exports.nunjucks = {
  3. enable: true,
  4. package: 'egg-view-nunjucks',
  5. };

Configure view plugins

egg-view defines the default configuration of config.view

root {String}

Root directory for template files is absolute path, with default value ${baseDir}/app/view.

egg-view supports having multiple directories, which are separated by ,.
In this case, it looks for template files from all the directories.

The configuration below is an example of multiple view directories:

  1. // config/config.default.js
  2. const path = require('path');
  3. module.exports = appInfo => {
  4. const config = {};
  5. config.view = {
  6. root: [
  7. path.join(appInfo.baseDir, 'app/view'),
  8. path.join(appInfo.baseDir, 'path/to/another'),
  9. ].join(',')
  10. };
  11. return config;
  12. };

cache {Boolean}

Cache template file paths, default value is true.
egg-view looks for template files from the directories that defined in root.
When a file matching given template path is found, the file’s full path will be cached
and reused afterward.
egg-view won’t search all directories again for the same template path.

mapping and defaultViewEngine

Every view engine has a view engine name defined when the plugin is enabled.
In view configuration, mapping defines the mapping
from template file’s extension name to view engine name.
For example, use Nunjucks engine to render .nj files.

  1. module.exports = {
  2. view: {
  3. mapping: {
  4. '.nj': 'nunjucks',
  5. },
  6. },
  7. };

egg-view uses the corresponding view engine according to the configuration above.

  1. await ctx.render('home.nj');

The mapping from file extension name to view engine must be defined.
Otherwise egg-view cannot find correct view engine.
Global configuration can be done with defaultViewEngine.

  1. // config/config.default.js
  2. module.exports = {
  3. view: {
  4. defaultViewEngine: 'nunjucks',
  5. },
  6. };

If a view engine cannot be found according to specified mapping,
the default view engine will be used.
For the applications that use only one view engine,
it’s recommended to set this option.

defaultExtension

When calling render(), the first argument should contain file extension name,
unless defaultExtension has been configured.

  1. // config/config.default.js
  2. module.exports = {
  3. view: {
  4. defaultExtension: '.nj',
  5. },
  6. };
  7. // render app/view/home.nj
  8. await ctx.render('home');

Render Page

egg-view provides three interfaces in Context.
All three returns a Promise:

  • render(name, locals) renders template file, and set the value to ctx.body.
  • renderView(name, locals) renders template file, returns the result and don’t set the value to any variable.
  • renderString(tpl, locals) renders template string, returns the result and don’t set the value to any variable.
  1. // {app_root}/app/controller/home.js
  2. class HomeController extends Controller {
  3. async index() {
  4. const data = { name: 'egg' };
  5. // render a template, path relate to `app/view`
  6. await ctx.render('home/index.tpl', data);
  7. // or manually set render result to ctx.body
  8. ctx.body = await ctx.renderView('path/to/file.tpl', data);
  9. // or render string directly
  10. ctx.body = await ctx.renderString('hi, {{ name }}', data, {
  11. viewEngine: 'nunjucks',
  12. });
  13. }
  14. }

When calling renderString, view engine should be specified unless defaultViewEngine has been defined.

Locals

In the process of rendering pages,
we usually need a variable to contain all information that is used in view template.
egg-view provides app.locals and ctx.locals.

  • app.locals is global, usually configured in app.js.
  • ctx.locals is per-request, and it merges app.locals.
  • ctx.locals can be assigned by modifying key/value or assigned with a new object. egg-view will merge the new object automatically in corresponding setter.
  1. // `app.locals` merged into `ctx.locals`
  2. ctx.app.locals = { a: 1 };
  3. ctx.locals.b = 2;
  4. console.log(ctx.locals); // { a: 1, b: 2 }
  5. // in the processing of a request, `app.locals` is merged into `ctx.locals` only at the first time `ctx.locals` being accessed
  6. ctx.app.locals = { a: 2 };
  7. console.log(ctx.locals); // already merged before, so output is still { a: 1, b: 2 }
  8. // pass a new object to `locals`. New object will be merged into `locals`, instead of replacing it. It's done by setter automatically.
  9. ctx.locals.c = 3;
  10. ctx.locals = { d: 4 };
  11. console.log(ctx.locals); // { a: 1, b: 2, c: 3, d: 4 }

In practical development, we usually don’t use these two objects in controller directly.
Instead, simply call ctx.render(name, data):

  • egg-view merges data into ctx.locals automatically.
  • egg-view injects ctx, request, helper into locals automatically.
  1. ctx.app.locals = { appName: 'showcase' };
  2. const data = { name: 'egg' };
  3. // will auto merge `data` to `ctx.locals`, output: egg - showcase
  4. await ctx.renderString('{{ name }} - {{ appName }}', data);
  5. // helper, ctx, request will auto inject
  6. await ctx.renderString('{{ name }} - {{ helper.lowercaseFirst(ctx.app.config.baseDir) }}', data);

Note:

  • ctx.locals is cached. app.locals is merged into it only at the first time that ctx.locals is accessed.
  • due to the ambiguity of naming, the ctx.state that is used in Koa is replaced by ctx.locals in Egg.js, i.e. ctx.state and ctx.locals are equivalent. It’s recommended to use the latter.

Helper

All functions that defined in helper can be directly used in templates.
See Extend for more details.

  1. // app/extend/helper.js
  2. exports.lowercaseFirst = str => str[0].toLowerCase() + str.substring(1);
  3. // app/controller/home.js
  4. await ctx.renderString('{{ helper.lowercaseFirst(name) }}', data);

Security

The built-in plugin egg-security provides common security helper functions, including helper.shtml / surl / sjs and so on. It’s strongly recommended to read Security.