This commit is contained in:
Flummi
2020-04-06 15:51:18 +02:00
parent 80f6dbf271
commit 8b9824e5fa
2 changed files with 17 additions and 15 deletions

View File

@ -1,7 +1,10 @@
export default new class {
snippets = {};
syntax = [
[ "each", t => `util.forEach(${t.slice(4).trim()},(value,key)=>{` ], // own valuename {{each items ->|as|=> item}}
#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", () => "});" ],
[ "if", t => `if(${t.slice(2).trim()}){` ],
[ "elseif", t => `}else if(${t.slice(6).trim()}){` ],
@ -18,15 +21,14 @@ export default new class {
else
throw new Error(`${o} is not a iterable object`);
}
render(tpl, data = {}) {
return new Function("util", "data", "let html = \"\";with(data){"
+ tpl.trim().replace(/[\n\r]/g, "").split(/{{\s*([^}]+)\s*}}/).filter(Boolean).map(t => {
for(let i = 0; i < this.syntax.length; i++)
if(t.indexOf(this.syntax[i][0]) === 0)
return this.syntax[i][1](t);
return `html+='${t}';`;
})
.join`` + "}return html.trim().replace(/>[\\n\\r\\s]*?</g, '><')")
render(tpl, data = {}, f) {
return new Function("util", "data", "let html = \"\";with(data){" + 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);
}
};