NestJS如何使用EJS模板引擎?

问题描述 投票:0回答:1

我想在 NestJS 中使用 EJS 作为我的模板引擎。使用 Express,我可以像这样在主文件中配置 EJS:

app.set("view engine", "ejs");

如何使用 NestJS 最好地实现它? Nestjs 不附带

.set
方法。

javascript node.js typescript nestjs ejs
1个回答
4
投票

您可以在

app.setViewEngine('ejs')
中的
main.ts
的帮助下进行配置。首先,安装它:

npm i ejs

通过下面的行,你会告诉 Express

public
目录将用于存储静态资产,
views
将包含模板,并且
ejs
模板引擎应该用于呈现 HTML 输出。

// 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();

下面是您将如何在控制器中呈现模板。您正在渲染

index.ejs
并将
message
作为参数传递。

// app.controller.ts
import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}

最后,您将在

message
中使用传递的
index.ejs
变量,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>App</title>
  </head>
  <body>
    <%= message %>
  </body>
</html>

您可以阅读更多官方文档.

© www.soinside.com 2019 - 2024. All rights reserved.