bound 内置支持 nunjucks 模板渲染。

配置

在 src/engine 下提供模板引擎配置

  1. import * as nunjucks from 'nunjucks'
  2. import { NestExpressApplication } from '@nestjs/platform-express'
  3. import config from '../config'
  4. export default function setEngine(app: NestExpressApplication) {
  5. // 详细配置信息,请参考 https://nunjucks.bootcss.com/api.html#environment
  6. const environment = nunjucks.configure(
  7. [`${config.APP}/view`], // 设置
  8. {
  9. autoescape: true,
  10. throwOnUndefined: false,
  11. trimBlocks: false,
  12. lstripBlocks: false,
  13. watch: true,
  14. noCache: process.env.NODE_ENV === "local" ? true : false,
  15. express: app
  16. }
  17. )
  18. app.engine('njk', environment.render)
  19. app.setViewEngine('njk')
  20. app.set("view cache", true);
  21. }

在入口 main.ts 中注入模板渲染能力

  1. // main.ts
  2. import { NestFactory } from '@nestjs/core'
  3. import { Logger } from '@nestjs/common'
  4. import { NestExpressApplication } from '@nestjs/platform-express'
  5. import { AppModule } from './app.module'
  6. import setEngine from './engine'
  7. import config from './config'
  8. async function bootstrap() {
  9. const app = await NestFactory.create<NestExpressApplication>(AppModule)
  10. ...
  11. ...
  12. setEngine(app) // 注入模板渲染能力
  13. await app.listen(config.PORT)
  14. Logger.log(`app is listening to ${config.PORT}`)
  15. }
  16. bootstrap();

使用

创建模板文件

在 /src/view 目录下创建文件,例如 index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  7. <title>nest</title>
  8. </head>
  9. <body>
  10. <div id="main">
  11. {{ name }}
  12. </div>
  13. </body>
  14. </html>

处理请求

在模块中处理请求:

  1. // user.controller.ts
  2. import { Controller, Get, Render } from '@nestjs/common'
  3. @Controller('user')
  4. export class UserController {
  5. @Get('/home')
  6. @Render('./index.html')
  7. async page() {
  8. return {
  9. name: 'bound'
  10. }
  11. }
  12. }

效果如下:
image.png
更多模板渲染相关的内容,请参考 MVC