Create simple template renderer
This commit is contained in:
28
utils/templates.jsm
Normal file
28
utils/templates.jsm
Normal 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;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user