admin管理员组

文章数量:1278983

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.

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.

Share Improve this question edited Jun 20, 2022 at 12:58 Youssouf Oumar 46.2k16 gold badges101 silver badges104 bronze badges asked Jun 20, 2022 at 12:13 Alessandro RhombergAlessandro Rhomberg 1653 silver badges11 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9

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/mon';

@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.

本文标签: javascriptHow to use EJS template engine with NestJSStack Overflow