# 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

Install the Ts.ED engines:

    The default template engine installed with Ts.ED is EJS (opens new window).

    import {Configuration} from "@tsed/di";
    
    @Configuration({
      views: {
        root: `../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

    TIP

    Supported engines is available here (opens new window).

    # 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

    # Supported template engines

    Some package has the same key name, @tsed/engines will load them according to the order number. For example with dust, @tsed/engines will try to use in this order: dustjs-helpers and dustjs-linkedin. If dustjs-helpers is installed, dustjs-linkedin will not be used by consolidate.

    Name Package Name / Order Website / State
    atpl (opens new window) npm install atpl (opens new window) -
    bracket (opens new window) npm install bracket-template (opens new window) -
    dot (opens new window) npm install dot (opens new window) (website) (opens new window)
    dust (opens new window) npm install dustjs-helpers (opens new window) (2) or
    npm install dustjs-linkedin (opens new window) (3)
    (website) (opens new window)
    ect (opens new window) npm install ect (opens new window) (website) (opens new window)
    ejs (opens new window) npm install ejs (opens new window) (website) (opens new window)
    hamlet (opens new window) npm install hamlet (opens new window) -
    hamljs (opens new window) npm install hamljs (opens new window) -
    haml-coffee (opens new window) npm install haml-coffee (opens new window) -
    handlebars (opens new window) npm install handlebars (opens new window) (website) (opens new window)
    hogan (opens new window) npm install hogan.js (opens new window) (website) (opens new window)
    htmling (opens new window) npm install htmling (opens new window) -
    jazz (opens new window) npm install jazz (opens new window) -
    just (opens new window) npm install just (opens new window) -
    liquor (opens new window) npm install liquor (opens new window) -
    lodash (opens new window) npm install lodash (opens new window) (website) (opens new window)
    marko (opens new window) npm install marko (opens new window) (website) (opens new window)
    mote (opens new window) npm install mote (opens new window) (website) (opens new window)
    mustache (opens new window) npm install mustache (opens new window) -
    nunjucks (opens new window) npm install nunjucks (opens new window) (website) (opens new window)
    plates (opens new window) npm install plates (opens new window) -
    pug (opens new window) npm install pug (opens new window) (website) (opens new window) / (formerly jade)
    ractive (opens new window) npm install ractive (opens new window) -
    react (opens new window) npm install react (opens new window) -
    slm (opens new window) npm install slm (opens new window) -
    squirrelly (opens new window) npm install squirrelly (opens new window) (website) (opens new window)
    swig (opens new window) npm install swig-templates (opens new window) (2) -
    teacup (opens new window) npm install teacup (opens new window) -
    templayed (opens new window) npm install templayed (opens new window) (website) (opens new window)
    twig (opens new window) npm install twig (opens new window) (wiki) (opens new window)
    twing (opens new window) npm install twing (opens new window) (website) (opens new window)
    underscore (opens new window) npm install underscore (opens new window) (website) (opens new window)
    vash (opens new window) npm install vash (opens new window) -
    velocityjs (opens new window) BETA (opens new window) (website) (opens new window)
    walrus (opens new window) npm install walrus (opens new window) (website) (opens new window)
    whiskers (opens new window) npm install whiskers (opens new window) -

    Note

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

    # Usage

    # Template Engine Instances

    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 nunjucksInstances = nunjucks.configure("./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

    # 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} from "@tsed/di";
        import {PlatformViews} from "@tsed/platform-views";
        
        @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
        19
        20

        # Alter render options

        You can alter the render options before rendering the view. Listen the $alterRenderOptions hook to inject data:

        import {Injectable, DIContext} from "@tsed/di";
        
        @Injectable()
        class AlterOptions {
          async $alterRenderOptions(options: Record<string, any>, $ctx: DIContext) {
            // only called when the response.render is called by your code
            options.alter = "alter";
            return options;
          }
        }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10

        # 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 {View} from "@tsed/platform-views";
        import {Get} from "@tsed/schema";
        import {Controller} from "@tsed/di";
        
        @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
        11
        12

        TIP

        Ts.ED enables cache by default in PRODUCTION profile.

        # Implement your own engine

        @tsed/engines let you register your own engine by using the @ViewEngine decorator. Here an is example of pug engine implementation:

        import {Engine, ViewEngine} from "@tsed/engines";
        
        @ViewEngine("pug", {
          requires: ["pug", "then-pug"] // multiple require is possible. Ts.ED will use the first module resolved from node_modules
        })
        export class PugEngine extends Engine {
          protected $compile(template: string, options: any) {
            return this.engine.compile(template, options);
          }
        
          protected async $compileFile(file: string, options: any) {
            return this.engine.compileFile(file, options);
          }
        }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14

        Last Updated: 3/19/2024, 7:27:06 AM

        Other topics