# Templating

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

# Installation

This example uses EJS as engine rendering. To use an other engine, see the documentation of the concerned project.

import {ServerLoader, ServerSettings} from "@tsed/common";
import bodyParser from "body-parser";
import compress from "compression";
import cons from "consolidate";
import cookieParser from "cookie-parser";
import methodOverride from "method-override";

const rootDir = __dirname;

@ServerSettings({
  rootDir,
  viewsDir: `${rootDir}/views`,
  mount: {
    "/rest": `${rootDir}/controllers/**/**.js`
  },
  componentsScan: [
    `${rootDir}/services/**/**.js`
  ]
})
class Server extends ServerLoader {
  $onInit() {
    this.set("views", this.settings.get("viewsDir")); // le repertoire des vues
    this.engine("ejs", cons.ejs);
  }

  async $beforeRoutesInit() {
    this.use(ServerLoader.AcceptMime("application/json"))
      .use(bodyParser.json())
      .use(bodyParser.urlencoded({
        extended: true
      }))
      .use(cookieParser())
      .use(compress({}))
      .use(methodOverride());
  }
}
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
26
27
28
29
30
31
32
33
34
35
36

The configuration engine is exactly the same as Express configuration engine.

# Usage

A template engine like EJS or Handlebars can be used to change the response returned by your endpoint. Like Express.js, you need to configure the templating engine so that you can use it later with the decorator.

Here is an example of a controller using the decorator:

import {Controller, Get, Render} from "@tsed/common";

@Controller("/events")
export class EventCtrl {

  @Get("/:id")
  @Render("eventCard.ejs")
  public get(): any {
    return {startDate: new Date(), name: "MyEvent"};
  }
}
1
2
3
4
5
6
7
8
9
10
11

And its view:

<h1><%- name %></h1>
<div>
    Start: <%- startDate %>
</div>
1
2
3
4

TIP

is an alias of .