Files
f0bm/src/inc/tpl.mjs
2021-04-17 10:43:23 +02:00

45 lines
1.8 KiB
JavaScript

import fs from "fs";
import path from "path";
import cfg from "./config.mjs";
export default new class {
#templates = {};
#syntax = [
[ "each", (t, _, args = t.slice(4).trim().split(" ")) => `util.forEach(${args[0]},(${(args[1] === "as" && args[2]) ? args[2] : "value"},key)=>{` ],
[ "/each", () => "});" ],
[ "if", t => `if(${t.slice(2).trim()}){` ],
[ "elseif", t => `}else if(${t.slice(6).trim()}){` ],
[ "else", () => "}else{" ],
[ "/if", () => "}" ],
[ "include", (t, data) => `html+='${this.render(cfg.websrv.cache ? t.slice(7).trim() : `views/${t.slice(7).trim()}`, data)}';` ],
[ "=", t => `html+=${t.slice(1).trim()};` ]
];
readdir(dir, root = dir, rel = dir.replace(`${root}/`, "")) {
for(const d of fs.readdirSync(`${path.resolve()}/${dir}`))
d.endsWith(".html")
? this.#templates[`${rel}/${d.split(".")[0]}`] = this.readtpl(dir, d)
: this.readdir(`${dir}/${d}`, root);
}
readtpl(dir, d) {
return fs.readFileSync(`${dir}/${d}`, "utf-8").replace(/\'/g, "\\'");
}
forEach(o, f) {
if(Array.isArray(o))
o.forEach(f);
else if(typeof o === "object")
Object.keys(o).forEach(k => f.call(null, o[k], k));
else
throw new Error(`${o} is not a iterable object`);
}
render(tpl, data = {}, f) {
return new Function("util", "data", "let html = \"\";with(data){" + (cfg.websrv.cache ? this.#templates[tpl] : this.readtpl(path.resolve(), `${tpl}.html`))
.trim()
.replace(/[\n\r]/g, "")
.split(/{{\s*([^}]+)\s*}}/)
.filter(Boolean)
.map(t => !(f = this.#syntax.filter(s => t.startsWith(s[0]))[0]) ? `html+='${t}';` : f[1](t, data))
.join("") + "}return html.trim().replace(/>[\\n\\r\\s]*?</g, '><')"
).bind(null, { forEach: this.forEach })(data);
}
};