Created
March 17, 2024 01:15
-
-
Save chrisbrocklesby/ba4b8574344faa26470c875f5dc9cde8 to your computer and use it in GitHub Desktop.
Handler Bars File Based Templating Engine - HBS
This file contains 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 "fs/promises"; | |
// Check if the templates directory exists. | |
try { | |
await fs.access("./templates"); | |
} catch (error) { | |
console.log("The templates directory does not exist."); | |
process.exit(1); | |
} | |
// Check if the pages directory exists. | |
try { | |
await fs.access("./templates/pages"); | |
} catch (error) { | |
console.log("The pages directory does not exist."); | |
process.exit(1); | |
} | |
// Check if the partials directory exists. | |
try { | |
await fs.access("./templates/partials"); | |
} catch (error) { | |
console.log("The partials directory does not exist."); | |
process.exit(1); | |
} | |
// Read the pages template files and register them. | |
var pages = {}; | |
var files = await fs.readdir("./templates/pages", { withFileTypes: true }); | |
for (var file of files) { | |
if (file.isDirectory()) { | |
var subfiles = await fs.readdir(`./templates/pages/${file.name}`); | |
for (var subfile of subfiles) { | |
var name = `${file.name}/${subfile.split(".")[0]}`; | |
var content = await fs.readFile(`./templates/pages/${file.name}/${subfile}`, "utf8"); | |
pages[name] = Handlebars.compile(content); | |
console.log(`Registered template: ${name}`); | |
} | |
} else { | |
var name = file.name.split(".")[0]; | |
var content = await fs.readFile(`./templates/pages/${file.name}`, "utf8"); | |
pages[name] = Handlebars.compile(content); | |
console.log(`Registered pages: ${name}`); | |
} | |
} | |
// Read the partials files and register them. | |
var partials = {}; | |
files = await fs.readdir("./templates/partials"); | |
for (var file of files) { | |
var name = file.split(".")[0]; | |
var content = await fs.readFile(`./templates/partials/${file}`, "utf8"); | |
partials[name] = Handlebars.compile(content); | |
Handlebars.registerPartial(name, partials[name]); | |
console.log(`Registered partial: ${name}`); | |
} | |
function render(template, data) { | |
try { | |
return pages[template](data); | |
} catch (error) { | |
console.log(`Error [${template}]: ${error.message}`); | |
} | |
} | |
export default render; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment