# Templating

View is a decorator which can be used on a controller method (endpoint). This decorator will use the data returned by the method, and the configured view to create the response.

# Configuration

Ts.ED is using by default consolidate (opens new window) under the hood.

The default template engine installed with Ts.ED is EJS (opens new window). If you want to use another engine, please refer to the engine documentation and consolidate (opens new window) to install the engine correctly.

import {Configuration} from "@tsed/common";

const rootDir = __dirname;

@Configuration({
  rootDir,
  viewsDir: `${rootDir}/views`,
  views: {
    root: `${rootDir}/views`,
    viewEngine: "ejs",
    extensions: { // optional
      "ejs": "ejs",
      "hbs": "handlebars"
    },
    options: {
      ejs: {} // global options for ejs engine. See official engine documentation for more details.
    }
  }
})
class Server {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

TIP

Supported engines is available here (opens new window).

WARNING

Ts.ED v7 will switch on @tsed/engines (opens new window) implementation. Consolidate will be removed from dependencies.

# Use @tsed/engines

To enable the new view engine feature, you have to install the @tsed/engines packages:

npm install @tsed/engines
1

# Options

export interface PlatformViewsSettings {
   /**
    * Views directory.
    */
   root?: string;
   /**
    * Enable cache. Ts.ED enables cache in PRODUCTION profile by default.
    */
   cache?: boolean;
   /**
    * Provide extensions mapping to match the expected engines.
    */
   extensions?: Partial<PlatformViewsExtensionsTypes>;
   /**
    * Default view engine extension.
    * Allow omitting extension when using View decorator or render method.
    */
   viewEngine?: string;
   /**
    * Options mapping for each engine.
    */
   options?: Partial<PlatformViewsEngineOptions>;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# Usage

# Template Engine Instances

# With Consolidate (deprecated)

Template engines are exposed via the consolidate.requires object, but they are not instantiated until you've called the consolidate[engine].render() method. You can instantiate them manually beforehand if you want to add filters, globals, mixins, or other engine features.

# With @tsed/engines

Template engines are exposed via the requires Map, but they are not instantiated until you've called the getEngine(engine).render() method. You can instantiate them manually beforehand if you want to add filters, globals, mixins, or other engine features.

# Nunjucks

import { Configuration } from "@tsed/common";
import nunjucks from "nunjucks";

const rootDir = Path.resolve(__dirname);

const nunjucksInstances = nunjucks.configure(`${rootDir}/views`);
nunjucksInstances.addFilter('foo', function () {
  return 'bar';
});

@Configuration({
  views: {
    root: `${rootDir}/views`,
    viewEngine: "nunjucks",
    extensions: {
      "njk": "nunjucks"
    },
    options: {
      nunjucks: {
        requires: nunjucksInstances
      }
    }
  },
})
export default class ShopApp {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# With decorator

Here is an example of a controller using the View decorator:

    TIP

    Like Express.js or Koa.js, View decorator uses express.response.locals or koa.context.state to populate data before rendering the template. See Locals decorator usage for more information.

    # With render method

    It's also possible to render a view by injecting and using PlatformResponse instance.

      # With PlatformViews

      Ts.ED provides the PlatformViews service to render views. In fact, View decorator uses PlatformResponse.render() method which itself uses the PlatformViews.render() method. It is useful if you want to render a template from a service.

      import {Inject, Injectable, PlatformViews} from "@tsed/common";
      
      @Injectable()
      export class MyService {
        @Inject()
        platformViews: PlatformViews;
      
        public async renderTemplate(data: any) {
          const result = await this.platformViews.render("view.ejs", {
            // some other options
            // ...
            ...data
          });
      
          console.log(result);
      
          return result;
        }
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18

      # Caching

      To enable caching, simply pass { cache: true } to the View decorator. All engines that consolidate.js / @tsed/engines (opens new window) implements I/O for, will cache the file contents, ideal for production environments.

      import {Controller, Get, View} from "@tsed/common";
      
      @Controller("/events")
      export class EventCtrl {
        @Get("/:id")
        @View("event.ejs", {cache: true})
        public get(): any {
          return {startDate: new Date(), name: "MyEvent"};
        }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10

      TIP

      Ts.ED enables cache by default in PRODUCTION profile.

      Last Updated: 9/17/2021, 8:57:54 AM

      Other topics