Robin gupta
Robin gupta

Reputation: 196

Unable to import handlebar file in nodejs

I am unable to import handlebars file in nodejs. Although it is importing the file but not compiling properly with given data.

here is my test.handlebars file code

<div>Hey {{firstname}} {{lastname}}</div>

and this is my index.js file code

const Handlebars = require("handlebars");
const testEmailTemplate = require("./email-templates/test.handlebars")
const template = Handlebars.compile(testEmailTemplate());

console.log(template({ firstname: "Nils", lastname: "Test" }));

And I am getting below output in console

<div>Hey</div>

expected output

<div>Hey Nils Test</div>

Note: - I don't want to use express-handlebar so please suggest some solution only with handlebars.

Upvotes: 1

Views: 2772

Answers (1)

Max Martynov
Max Martynov

Reputation: 739

The require() method expects to get a Node.js module. But in your case, the target file is HTML, and you need to get the content of the file as plain text to use it further. Use for that fs module and it's method fs.readFile() or fs.readFileSync()

The result code should look like:

const fs = require("fs");
const Handlebars = require("handlebars");
const testEmailTemplate = fs.readFileSync("./email-templates/test.handlebars", "utf-8")
const template = Handlebars.compile(testEmailTemplate);

console.log(template({ firstname: "Nils", lastname: "Test" }));

Info: What is require?

Upvotes: 2

Related Questions