forked from f0ck/f0ckv2
.
This commit is contained in:
@ -1,18 +1,24 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
export default new class {
|
||||
snippets = {};
|
||||
#templates = {};
|
||||
#syntax = [
|
||||
[ "each", t => {
|
||||
const tmp = t.slice(4).trim().split(" ");
|
||||
return `util.forEach(${tmp[0]},(${(tmp[1] === "as" && tmp[2]) ? tmp[2] : "value"},key)=>{`;
|
||||
} ],
|
||||
[ "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 => `html+=util.snippets["${t.slice(7).trim()}"];`],
|
||||
[ "include", t => `html+=util.tpl["${t.slice(7).trim()}"];`],
|
||||
[ "=", 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.readdir(`${dir}/${d}`, root);
|
||||
}
|
||||
forEach(o, f) {
|
||||
if(Array.isArray(o))
|
||||
o.forEach(f);
|
||||
@ -22,13 +28,13 @@ 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){" + tpl
|
||||
return new Function("util", "data", "let html = \"\";with(data){" + this.#templates[tpl]
|
||||
.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))
|
||||
.join("") + "}return html.trim().replace(/>[\\n\\r\\s]*?</g, '><')")
|
||||
.bind(null, { forEach: this.forEach, snippets: this.snippets })(data);
|
||||
.join("") + "}return html.trim().replace(/>[\\n\\r\\s]*?</g, '><')"
|
||||
).bind(null, { forEach: this.forEach, tpl: this.#templates })(data);
|
||||
}
|
||||
};
|
||||
|
Reference in New Issue
Block a user