Nestjs中的模板引擎配置和express中的模板引擎配置基本是一样的,下面我们以ejs为例给大家讲解Nest模板引擎配置
EJS是一个JavaScript模板库,用来从JSON数据中生成HTML字符串。Koa2框架中ejs可以把数据库查询的数据渲染到模板上面,实现一个动态网站。
Nestjs模板引擎配置官方文档:https://docs.nestjs.com/techniques/mvc
1、安装对应的模板引擎 比如ejs
cnpm i ejs --save
2、配置模板引擎
app.setBaseViewsDir(join(__dirname, '..', 'views')) // 放视图的文件
app.setViewEngine('ejs');	
nestjs模板引擎配置完整代码:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import {join} from 'path';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // app.useStaticAssets('public'); 
  app.useStaticAssets(join(__dirname, '..', 'public'),{
    prefix: '/static/',   //设置虚拟路径
 }); 
  app.setBaseViewsDir(join(__dirname, '..', 'views')) // 放视图的文件
  app.setViewEngine('ejs');
  await app.listen(3000);
}
bootstrap();
 
3、渲染页面
Nestjs中 Render装饰器可以渲染模板
import { Get, Controller, Render } from '@nestjs/common';
@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}
4、项目根目录新建views目录然后新建index.ejs
Document 这是ejs演示代码
<%=message%>
import { Controller, Get, Post, Body,Response, Render} from '@nestjs/common';
@Controller('user')
export class UserController {
    @Get()
    @Render('default/user')
    index(){
       return {"name":"张三"};
    }
    @Post('doAdd')
    doAdd(@Body() body,@Response() res){
        console.log(body);
        res.redirect('/user');  //路由跳转        
    }    
}
模板
Document ![]()