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:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarsruntime.js:403:11) at Object.invokePartialWrapper [as invokePartial] (C:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarsruntime.js:82:39) at Object.eval (eval at createFunctionContext (C:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarscompilerjavascript-compiler.js:265:23), <anonymous>:11:28) at main (C:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarsruntime.js:230:22) at ret (C:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarsruntime.js:250:12) at ret (C:Usersdnbyyyyready-to-readnode_moduleshandlebarslibhandlebarscompilercompiler.js:548:21) at _Reply.viewHandlebars (C:Usersdnbyyyyready-to-readnode_modules@fastifyviewindex.js:468:14) at _Reply.view (C:Usersdnbyyyyready-to-readnode_modules@fastifyviewindex.js:127:22) at C:Usersdnbyyyyready-to-readnode_modules@nestjscorerouterrouter-execution-context.js:159:24 at C:Usersdnbyyyyready-to-readnode_modules@nestjscorerouterrouter-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
D Bystrov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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,
},
},
});