Create simple template renderer

This commit is contained in:
2025-10-19 01:59:17 +08:00
parent 941d93401c
commit eabc75c8de
9 changed files with 165 additions and 46 deletions

28
utils/templates.jsm Normal file
View File

@@ -0,0 +1,28 @@
import fs from "fs";
import path from "path";
export function createTemplateRenderer({
baseDir = path.resolve("templates"),
useCache = true,
} = {}) {
const cache = {};
return function render(fileName, vars = {}) {
const filePath = path.join(baseDir, fileName);
let template;
if (useCache && cache[filePath]) {
template = cache[filePath];
} else {
template = fs.readFileSync(filePath, "utf8");
if (useCache) cache[filePath] = template;
}
let html = template;
for (const [key, value] of Object.entries(vars)) {
html = html.replace(new RegExp(`{{${key}}}`, "g"), value);
}
return html;
};
}