Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs: multiple views directory

I am developing an MVC app using nestJs framework, and I used the hbs template-engine.

According to the documentation I have to use this configuration to make nestjs able to serve views:

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?

like image 891
maroodb Avatar asked May 26 '26 03:05

maroodb


1 Answers

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:

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() {
like image 195
Kim Kern Avatar answered May 28 '26 18:05

Kim Kern