diff --git a/src/inc/tpl.mjs b/src/inc/tpl.mjs index 03f9f47..8a20460 100644 --- a/src/inc/tpl.mjs +++ b/src/inc/tpl.mjs @@ -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]*?<')") + 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]*?<')") .bind(null, { forEach: this.forEach, snippets: this.snippets })(data); } }; diff --git a/views/index.html b/views/index.html index 7b69c9a..ce0efc1 100644 --- a/views/index.html +++ b/views/index.html @@ -11,11 +11,11 @@ {{include navbar}}