This commit is contained in:
Flummi
2021-04-17 10:43:23 +02:00
parent d553e71b50
commit 65454961ce
54 changed files with 1996 additions and 25454 deletions

View File

@ -1,5 +1,6 @@
import fs from "fs";
import path from "path";
import cfg from "./config.mjs";
export default new class {
#templates = {};
@ -10,15 +11,18 @@ export default new class {
[ "elseif", t => `}else if(${t.slice(6).trim()}){` ],
[ "else", () => "}else{" ],
[ "/if", () => "}" ],
[ "include", (t, data) => `html+='${this.render(t.slice(7).trim(), data)}';` ],
[ "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]}`] = fs.readFileSync(`${dir}/${d}`, "utf-8").replace(/\'/g, "\\'")
? 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);
@ -28,7 +32,7 @@ export default new class {
throw new Error(`${o} is not a iterable object`);
}
render(tpl, data = {}, f) {
return new Function("util", "data", "let html = \"\";with(data){" + this.#templates[tpl]
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*}}/)