bound 内置支持 nunjucks 模板渲染。
配置
在 src/engine 下提供模板引擎配置
import * as nunjucks from 'nunjucks'import { NestExpressApplication } from '@nestjs/platform-express'import config from '../config'export default function setEngine(app: NestExpressApplication) {// 详细配置信息,请参考 https://nunjucks.bootcss.com/api.html#environmentconst environment = nunjucks.configure([`${config.APP}/view`], // 设置{autoescape: true,throwOnUndefined: false,trimBlocks: false,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);}
在入口 main.ts 中注入模板渲染能力
// main.tsimport { NestFactory } from '@nestjs/core'import { Logger } from '@nestjs/common'import { NestExpressApplication } from '@nestjs/platform-express'import { AppModule } from './app.module'import setEngine from './engine'import config from './config'async function bootstrap() {const app = await NestFactory.create<NestExpressApplication>(AppModule)......setEngine(app) // 注入模板渲染能力await app.listen(config.PORT)Logger.log(`app is listening to ${config.PORT}`)}bootstrap();
使用
创建模板文件
在 /src/view 目录下创建文件,例如 index.html
<!DOCTYPE html><html lang="en"><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>nest</title></head><body><div id="main">{{ name }}</div></body></html>
处理请求
在模块中处理请求:
// user.controller.tsimport { Controller, Get, Render } from '@nestjs/common'@Controller('user')export class UserController {@Get('/home')@Render('./index.html')async page() {return {name: 'bound'}}}
效果如下:
更多模板渲染相关的内容,请参考 MVC。
