使用 Handlebars 部分(nestjs + Fastify)时出现问题

问题描述 投票:0回答:1

我正在尝试使用 Handlebars 将项目中的静态内容替换为模板。我的项目名称是可读的,所以我有以下文件结构:

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

这是我的 main.ts 文件:

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();

我不断收到此错误:

[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

试图弄乱 main.ts 中“partials”文件夹的路径,但收到另一个错误,说我正在尝试将目录作为文件打开

typescript nestjs handlebars.js fastify
1个回答
0
投票

您应该按照与模板相同的方式配置部分路径:

const templatesDir = join(__dirname, '..', 'views');
const partialsDir = join(templatesDir, 'partials');

app.setViewEngine({
  ...
  templates: templatesDir,
  options: {
    partials: {
      dir: partialsDir,
    },
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.