Templating

@ResponseView() or @Render() is a decorator that 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.

templating-engine

Installation

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

import Path = require("path");
const rootDir = Path.resolve(__dirname);

@ServerSettings({
   rootDir,
   mount: {
      '/rest': `${rootDir}/controllers/**/**.js`
   },
   componentsScan: [
       `${rootDir}/services/**/**.js`
   ]
})
class Server extends ServerLoader {

    async $onMountingMiddlewares()  {

        const cookieParser = require('cookie-parser'),
            bodyParser = require('body-parser'),
            compress = require('compression'),
            methodOverride = require('method-override'),
            session = require('express-session');

        this.use(ServerLoader.AcceptMime("application/json"))
            .use(bodyParser.json())
            .use(bodyParser.urlencoded({
                extended: true
            }))
            .use(cookieParser())
            .use(compress({}))
            .use(methodOverride());

        // EJS Engine Setting
        this.engine('.html', require('ejs').__express)
            .set('views', './views')
            .set('view engine', 'html');
    }
}
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
37

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

Use decorator

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

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

@Render() is an alias of @ResponseView().

Create your template

views/eventCard.html

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