Struggling with integrating Handlebars partials in a NestJS and Fastify environment

I am in the process of enhancing my project by replacing static content with templates using Handlebars. The project is named ready-to-read, and the file structure looks like the following:

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

Take a look at 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();

Encountering the following error repeatedly:

[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

Attempting to modify the path to the 'partials' folder in main.ts, but ended up with another error indicating that the directory is being opened as a file

Answer №1

To ensure proper configuration of partials, follow the same steps as you did with templates:

const templatesDirectory = join(__dirname, '..', 'views');
const partialsDirectory = join(templatesDirectory, 'partials');

app.setViewEngine({
  ...
  templates: templatesDirectory,
  options: {
    partials: {
      directory: partialsDirectory,
    },
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript to transform types: Array of objects with keys Kn and values Vn to an object with keys Kn and values Vn

I am looking to create a function that can process tuples with a specific structure like so: type Input = [ { key: K1, value: V1 }, { key: K2, value: V2 }, { key: K3, value: V3 }, // ... { key: KN, value: VN } ] The function should then output ...

Creating an object with mapped properties from enumeration values using Typescript

I am trying to find a way to automatically create an object with values computed during compilation using enumeration values and pre-defined function calls. The basic concept is to associate certain arguments of a function with keys. For example, consider ...

Angular: Utilizing the new HttpClient to map HTTP responses

Within my application, I have a standard API service that communicates with the backend using requests structured like this: post<T>(url: string, jsonObject: object): Observable<T> { return this.http.post<T>(url, JSON.stringify(json ...

What distinguishes ES6 from ES2015 in the TypeScript compiler option `--libs`?

Can you explain the distinction between ES6 and ES2015 in the TypeScript compiler option here? Also, what does --libs do? https://i.sstatic.net/iUv8t.png ...

Issue with Typescript express application utilizing express-openid-connect wherein cookies are not being retained, resulting in an infinite loop of redirects

For a while now, I've been facing a block with no resolution in sight for this particular issue. Hopefully, someone out there can lend a hand. Background I have a TS express application running on Firebase functions. Additionally, I utilize a custom ...

Utilizing a fixed array as the data source for a mat-table

I am currently working on implementing the Angular Material table into my project. I am encountering an issue when trying to define the [dataSource]="data", even though I am using code similar to the examples provided. My question may seem basic, but my t ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

The HTTP DELETE request encountered a TypeError, stating that error.json is not a valid function

Within my Angular application, there is a feature that involves a "delete button". When this button is clicked, a confirmation popup appears asking the user if they are certain they want to proceed with the deletion. If the user confirms by clicking ' ...

Angular 2 event emitter falling behind schedule

I am currently utilizing Angular 2 beta 6. The custom event I created is not being captured import {Component, OnInit, EventEmitter} from 'angular2/core'; import {NgForm} from 'angular2/common'; import {Output} from "angular2/core" ...

How can the file system module (fs) be utilized in Angular 7?

Hello, I am currently working with Angular 7. I recently attempted to utilize the fs module in Typescript to open a directory. However, I encountered an error message stating: "Module not found: Error: Can't resolve fs". Despite having types@node and ...

Angular 4 and Webpack: Compilation Error

After successfully running npm install, I encountered an error when trying to execute ng serve. Despite multiple attempts and troubleshooting, the issue persists. Could this be related to Angular versions? Interestingly, the same project runs smoothly on ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

Why can't I omit <someUnion, oneInterface> in TypeScript?

Kindly review this simple example: interface A { a: number; } interface B { b: number; } interface C { c: number; } type ABC = A | B | C; type omitA = Omit<ABC, A>; https://i.sstatic.net/5Mun4.png Unfortunately, I am unable to exclude an i ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Utilize Typescript to expand the functionality of the Express Request object

Is there a way to add a custom property to the request object in Express middleware using TypeScript without resorting to bracket notation? I am struggling to find a solution that satisfies this requirement. I would ideally like to achieve something like ...

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...

Purge React Query Data By ID

Identify the Issue: I'm facing a challenge with invalidating my GET query to fetch a single user. I have two query keys in my request, fetch-user and id. This poses an issue when updating the user's information using a PATCH request, as the cach ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

The system is failing to recognize the union data type

My code defines various types as follows: export type Property = | BooleanProperty | NumberProperty | IntegerProperty | StringProperty | ObjectProperty | ArrayProperty; export interface OneOf { oneOf: PropertyOrKeyword[]; } export interface ...