nest 模板引擎配置

时间:2023-01-04 浏览:181 分类:NestJS

安装模板引擎

npm i ejs --save

配置:

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {join} from 'path';

async function bootstrap() {  const app = await NestFactory.create(AppModule);

  app.setBaseViewsDir(join(__dirname, '..', 'views')) // 放视图的文件
  app.setViewEngine('ejs'); //模板渲染引擎

  await app.listen(9000);
}
bootstrap();

网页文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
   <h3>模板引擎</h3>
    <%=message%>
</body>
</html>

渲染页面

mport { Controller, Get, Render } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  @Get()
  @Render('index')  //使用render渲染模板引擎,参数就是文件路径:views文件夹下的index.ejs
  getUser(): any {
    return {message: "hello word"}   //只有返回参数在模板才能获取,如果不传递参数,必须返回一个空对象
  }
}