This commit is contained in:
Flummi
2020-04-05 18:47:09 +02:00
parent a202ae2e69
commit 29329702da
10 changed files with 188 additions and 234 deletions

30
src/inc/tpl.mjs Normal file
View File

@ -0,0 +1,30 @@
export default new class {
syntax = [
[ "each", t => `util.forEach(${t.slice(4).trim()},($value,$key)=>{` ],
[ "/each", () => "});" ],
[ "if", t => `if(${t.slice(2).trim()}){` ],
[ "elseif", t => `}else if(${t.slice(6).trim()}){` ],
[ "else", () => "}else{" ],
[ "/if", () => "}" ],
[ "=", t => `html+=${t.slice(1).trim()};` ]
];
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) {
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, '><')")
.bind(null, { forEach: this.forEach })(data);
}
};