# Templating

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

# Installation

This example use EJS as engine rendering. To use 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

Template feature depending on the engine rendering use by your application. Ts.ED provide decorator to define a view which will be used by the Endpoint to generate the response.

Here an example of a controller which use 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 his view:

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

TIP

is an alias of .