29 lines
664 B
JavaScript
29 lines
664 B
JavaScript
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;
|
|
};
|
|
}
|