简体   繁体   English

NestJs:多视图目录

[英]NestJs: multiple views directory

I am developing an MVC app using nestJs framework, and I used the hbs template-engine. 我正在使用nestJs框架开发MVC应用程序,并且使用了hbs模板引擎。

According to the documentation I have to use this configuration to make nestjs able to serve views: 根据文档,我必须使用此配置来使nestjs能够提供视图:

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(3000);
}

This configuration assumes that all views are located in one directory (views) but what if every module has its own views? 此配置假定所有视图都位于一个目录(视图)中,但是如果每个模块都有自己的视图怎么办?

Since v5.7.0 从v5.7.0开始

You can set an array of directories: 您可以设置目录数组:

app.setBaseViewsDir([
  join(__dirname, '..', 'users/views'), 
  join(__dirname, '..', 'books/views'),
]);

Before v5.7.0 v5.7.0之前

In express, you can set an array of base path directories : 在Express中,您可以设置基本路径目录的数组

A directory or an array of directories for the application's views. 应用程序视图的目录或目录数组。 If an array, the views are looked up in the order they occur in the array. 如果是数组,则按在数组中出现的顺序查找视图。

However, the typings in nest.js do not allow for an array, see issue . 但是,nest.js中的类型不允许使用数组,请参见issue I've created a pull request , that will change that. 我创建了一个pull请求 ,它将改变这种情况。

Until the pull request is merged, you can do: 在合并请求合并之前,您可以执行以下操作:

app.setBaseViewsDir([
    join(__dirname, '..', 'users/views'), 
    join(__dirname, '..', 'books/views'),
  ] as any);

As soon as the pull request is merged, you can remove the as any . 合并拉取请求后,您就可以删除as any

I'm assuming you have an app structure similar to this: 我假设您的应用程序结构与此类似:

src
  main.ts
  /users
       users.controller.ts
       /views
         my-view.hbs
  /books
       books.controller.ts
       /views
         my-view.hbs

Then you can set the base view dir to src : 然后,您可以将基本视图目录设置为src

app.setBaseViewsDir(__dirname);

And reference the view with its relative path in your controllers: 并在控制器中引用视图及其相对路径:

@Controller('users')
export class UsersController {

  @Render('users/views/my-view')
           ^^^^^^^^^^^^^^^^^^^
  @Get()
  async getMyView() {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM