NestJS+Fastify项目中Handlebars模板片段引用失败问题
NestJS + Fastify + Handlebars 模板部分加载失败排查与解决
项目文件结构
ready-to-read -public -src -views --(若干 .hbs 文件) --partials ---(若干 .hbs 文件)
当前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
问题说明
尝试调整partials文件夹路径后,又出现“试图将目录当作文件打开”的错误,无法正常加载Handlebars模板部分。
解决方法
方法1:修正partials路径配置(推荐)
Fastify的@fastify/view插件中,partials的dir需要配置为绝对路径,避免相对路径解析错误。修改main.ts中的视图引擎配置:
app.setViewEngine({ engine: { handlebars: require('handlebars'), }, templates: join(__dirname, '..', 'views'), options: { partials: { // 使用绝对路径指向partials文件夹 dir: join(__dirname, '..', 'views', 'partials'), // 可选:指定模板扩展名,避免引用时重复添加后缀 extensions: '.hbs' }, }, });
方法2:修正模板中的partial引用方式
如果模板中引用partial时带了.hbs后缀(比如{{> shared-scripts-styles.hbs}}),需要去掉后缀,改为:
{{> shared-scripts-styles}}
Handlebars会自动根据配置的路径和扩展名匹配对应的文件,添加后缀会导致查找路径错误。
方法3:检查文件存在性
确认views/partials目录下确实存在shared-scripts-styles.hbs文件,文件名大小写与模板中的引用完全一致(Windows系统不区分大小写,但部署到Linux环境会有问题,建议保持一致)。
内容的提问来源于stack exchange,提问作者D Bystrov
相关产品推荐
相关产品推荐

