添加nunjucks模板引擎
1、添加 nunjucks npm 包
2、根目录新建views文件夹存放模板(和src同目录),并新建index.njk
3、main.ts内
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express'; import { join } from 'path' import * as nunjucks from 'nunjucks'
async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule);
// 获取根目录nest-cnode const rootDir = join(__dirname, '..');
const environment = nunjucks.configure( [ join(rootDir, "views") ], { autoescape: true, throwOnUndefined: false, trimBlocks: true, lstripBlocks: false, watch: true, noCache: process.env.NODE_ENV === "local" ? true : false, express: app } ); app.engine("njk", environment.render); app.setViewEngine("njk"); app.set("view cache", true);
await app.listen(3000); } bootstrap();
|
4、修改src/app.controller.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import { Controller, Get, Post,Render } from '@nestjs/common'; import { AppService } from './app.service';
@Controller() export class AppController { constructor(private readonly appService: AppService) {}
// @Get() // getHello(): string { // return this.appService.getHello(); // }
@Get() @Render('index') root() { return { message: 'Hello world!' }; }
@Post() addHello(){ return { test: true } } }
|
5、index.njk内修改部分njk的语法,刷新浏览器则可看到效果