# 模型-视图-控制器

来源：https://docs.nestjs.com/http/mvc

默认情况下，Nest 底层使用 [Express](https://github.com/expressjs/express) 库。因此，在 Express 中使用 MVC（Model-View-Controller，模型-视图-控制器）模式的所有技巧同样适用于 Nest。

首先，用 [CLI](https://github.com/nestjs/nest-cli) 工具脚手架一个新 Nest 应用：

```bash
$ npm i -g @nestjs/cli
$ nest new project
```

要创建 MVC 应用，你还需要一个[模板引擎](https://expressjs.com/en/guide/using-template-engines.html)来渲染 HTML 视图：

```bash
$ npm install --save hbs
```

本示例使用 `hbs`（[Handlebars](https://github.com/pillarjs/hbs#readme)）引擎，你也可以用任何符合需求的引擎。安装完成后，用以下代码配置 Express 实例：

```typescript
@@filename(main)
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
  );

  app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
  app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

这告诉 Express：`public` 目录存放静态资源，`views` 目录存放模板，`hbs` 模板引擎负责渲染 HTML 输出。

> info **提示** 同样的调用也适用于 `NodeAdapter`：改用 `new NodeAdapter()` 和 `NestNodeApplication` 类型创建应用即可（见 [Node 适配器](/http/performance#node-adapter)）。Node 适配器支持 `@Render()` 装饰器，但不支持下文[动态模板渲染](/http/mvc#dynamic-template-rendering)中用到的 `res.render()` 方法。

#### 模板渲染

现在创建一个 `views` 目录，并在其中放置 `index.hbs` 模板。该模板打印控制器传入的 `message`：

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>App</title>
  </head>
  <body>
    {{ message }}
  </body>
</html>
```

接着打开 `app.controller` 文件，把内容替换为以下代码：

```typescript
@@filename(app.controller)
import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}
```

这段代码在 `@Render()` 装饰器中指定要使用的模板，路由处理方法的返回值会传给模板进行渲染。返回值是一个带 `message` 属性的对象，与模板中的 `message` 占位符对应。

应用运行期间，用浏览器访问 `http://localhost:3000`，你应该会看到 `Hello world!` 消息。

#### 添加布局

`hbs` 引擎支持布局（layout）：即各个视图渲染进去的共享外层模板。要使用布局，请用 `setLocal()` 方法设置 `layout` 局部变量（这是 Nest 对 Express [app.locals](https://expressjs.com/en/5x/api.html#app.locals) 的封装）。把前面的代码修改如下：

```typescript
@@filename(main)
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';
import { AppModule } from './app.module.js';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
  );

  app.setLocal('layout', 'layouts/app');
  app.useStaticAssets(join(import.meta.dirname, '..', 'public'));
  app.setBaseViewsDir(join(import.meta.dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

接着在 `views` 中创建 `layouts` 文件夹，并添加内容如下的 `app.hbs` 文件：

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>App</title>
  </head>
  <body>
    {{{ body }}}
  </body>
</html>
```

然后把 `index.hbs` 更新为：

```html
{{ message }}
```

最终的文件结构如下：

<div class="file-tree">
  <div class="item">views</div>
  <div class="children">
    <div class="item">layouts</div>
    <div class="children">
      <div class="item">app.hbs</div>
    </div>
    <div class="item">index.hbs</div>
  </div>
</div>

#### 动态模板渲染

如果应用逻辑必须动态决定渲染哪个模板，请使用 `@Res()` 装饰器，并在路由处理器中提供视图名，而不是写在 `@Render()` 装饰器里：

> info **提示** 当 Nest 检测到 `@Res()` 装饰器时，它会注入库特有的 `response` 对象，你可以用它动态渲染模板。关于 `response` 对象的更多内容见 [Express API 参考](https://expressjs.com/en/api.html)。

```typescript
@@filename(app.controller)
import { Get, Controller, Res, Render } from '@nestjs/common';
import type { Response } from 'express';
import { AppService } from './app.service.js';

@Controller()
export class AppController {
  constructor(private appService: AppService) {}

  @Get()
  root(@Res() res: Response) {
    return res.render(
      this.appService.getViewName(),
      { message: 'Hello world!' },
    );
  }
}
```

#### 示例

可运行的示例见 [15-mvc 示例](https://github.com/nestjs/nest/tree/master/sample/15-mvc)。

#### Fastify

如 [HTTP 适配器](/http/performance)一章所述，你可以为 Nest 使用任何兼容的 HTTP 提供者。其中一个库就是 [Fastify](https://github.com/fastify/fastify)。要用 Fastify 创建 MVC 应用，请安装以下包：

```bash
$ npm i --save @fastify/static @fastify/view handlebars
```

接下来的步骤与 Express 几乎相同，只有少量平台特有的差异。安装完成后，打开 `main.ts` 文件并更新其内容：

```typescript
@@filename(main)
import { NestFactory } from '@nestjs/core';
import { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { join } from 'node:path';
import Handlebars from 'handlebars';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  app.useStaticAssets({
    root: join(import.meta.dirname, '..', 'public'),
    prefix: '/public/',
  });
  app.setViewEngine({
    engine: {
      handlebars: Handlebars,
    },
    templates: join(import.meta.dirname, '..', 'views'),
  });
  await app.listen(process.env.PORT ?? 3000);
}
await bootstrap();
```

Fastify 的 API 有几处差异，但这些方法调用的最终结果相同。一个显著差异是：在 Fastify 下，传给 `@Render()` 装饰器的模板名必须包含文件扩展名：

```typescript
@@filename(app.controller)
import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index.hbs')
  root() {
    return { message: 'Hello world!' };
  }
}
```

另一种做法是用 `@Res()` 装饰器直接注入响应，并指定你想渲染的视图，如下所示：

```typescript
import { Get, Res } from '@nestjs/common';
import type { FastifyReply } from 'fastify';

@Get()
root(@Res() res: FastifyReply) {
  return res.view('index.hbs', { message: 'Hello world!' });
}
```

应用运行期间，用浏览器访问 `http://localhost:3000`，你应该会看到 `Hello world!` 消息。

#### 示例

可运行的示例见 [17-mvc-fastify 示例](https://github.com/nestjs/nest/tree/master/sample/17-mvc-fastify)。
