typescriptnestjshandlebars.jsfastify

Trouble using Handlebars partials (nestjs + Fastify)


I'm trying to replace static content in my project with templates using Handlebars. The name of my project is ready-to-read, so I have the following file structure:

ready-to-read
-public
-src
-views
--(some .hbs files)
--partials
---(some .hbs files)

Here is my main.ts file:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import {
  NestFastifyApplication,
  FastifyAdapter,
} from '@nestjs/platform-fastify';
import { join } from 'path';

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

  app.setViewEngine({
    engine: {
      handlebars: require('handlebars'),
    },
    templates: join(__dirname, '..', 'views'),
    options: {
      partials: {
        dir: 'partials',
      },
    },
  });

  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT') || 3000;
  await app.listen(port);
}
bootstrap();

I keep getting this error:

[Nest] 2400 - 24.04.2024, 17:27:31 ERROR [ExceptionsHandler] The partial shared-scripts-styles.hbs could not be found Error: The partial shared-scripts-styles.hbs could not be found at Object.invokePartial (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\runtime.js:403:11) at Object.invokePartialWrapper [as invokePartial] (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\runtime.js:82:39) at Object.eval (eval at createFunctionContext (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\compiler\javascript-compiler.js:265:23), <anonymous>:11:28) at main (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\runtime.js:230:22) at ret (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\runtime.js:250:12) at ret (C:\Users\dnbyyyy\ready-to-read\node_modules\handlebars\lib\handlebars\compiler\compiler.js:548:21) at _Reply.viewHandlebars (C:\Users\dnbyyyy\ready-to-read\node_modules\@fastify\view\index.js:468:14) at _Reply.view (C:\Users\dnbyyyy\ready-to-read\node_modules\@fastify\view\index.js:127:22) at C:\Users\dnbyyyy\ready-to-read\node_modules\@nestjs\core\router\router-execution-context.js:159:24 at C:\Users\dnbyyyy\ready-to-read\node_modules\@nestjs\core\router\router-execution-context.js:47:13

Tried to mess with a path to 'partials' folder in main.ts, but got another error saying that I'm trying to open the directory as a file


Solution

  • You should configure the path to partials the same way as you did with templates:

    const templatesDir = join(__dirname, '..', 'views');
    const partialsDir = join(templatesDir, 'partials');
    
    app.setViewEngine({
      ...
      templates: templatesDir,
      options: {
        partials: {
          dir: partialsDir,
        },
      },
    });