Created
January 21, 2025 18:02
-
-
Save nikoheikkila/faf63b2b43cdcb6abbc1dddfa66a0a41 to your computer and use it in GitHub Desktop.
TypeScript: Compiling Handlebars templates with custom data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Handlebars from "handlebars"; | |
import fs from "node:fs"; | |
type Data = Record<string, unknown>; | |
type Template = (data: Data) => string; | |
export default class Templater { | |
private readonly template: Template; | |
public static using(templatePath: string): Templater { | |
const templateString = fs.readFileSync(templatePath, "utf8"); | |
return new Templater(templateString); | |
} | |
public render(data: Data): string { | |
return this.template(data); | |
} | |
public save(data: Data, outputPath: string): Templater { | |
const rendered = this.render(data); | |
fs.writeFileSync(outputPath, rendered); | |
return this; | |
} | |
private constructor(templateString: string) { | |
this.template = Handlebars.compile(templateString, { | |
strict: true | |
}); | |
} | |
} | |
/* Example 1: Rendering and displaying template */ | |
const readme = Templater | |
.using("README.md.tpl") | |
.render({ name: "World" }); | |
console.log(readme); | |
/* Example 2: Saving rendered template directly to file */ | |
const templater = Templater | |
.using("README.md.tpl") | |
.save({ name: "World" }, "README.md"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment