I would like to use EJS as my template engine in NestJS. With Express I can configure EJS in the main file like this:
app.set("view engine", "ejs");
How can I best implement this with NestJS? Nestjs does not ship with a .set
method.
You can configure that with the help of app.setViewEngine('ejs')
in main.ts
. First, install it:
npm i ejs
With the lines below, you would have told Express that the public
directory will be used for storing static assets, views
will contain templates, and the ejs
template engine should be used to render HTML output.
// main.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
/*
Here it's assumed that public and views are in the root directory,
alongside src. You can put them wherever you want,
just use the correct path if you use another folder.
*/
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
And below is how you would render a template in a Controller. You are rendering index.ejs
and passing message
as a parameter.
// app.controller.ts
import { Get, Controller, Render } from '@nestjs/common';
@Controller()
export class AppController {
@Get()
@Render('index')
root() {
return { message: 'Hello world!' };
}
}
Finally, you would use that passed message
variable inside index.ejs
like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
<%= message %>
</body>
</html>
You can read more on the official documentation.