tpl: include snippets

This commit is contained in:
Flummi
2020-04-06 13:16:21 +02:00
parent 47cc62b767
commit da9d29e727
2 changed files with 42 additions and 75 deletions

View File

@ -1,11 +1,13 @@
export default new class {
snippets = {};
syntax = [
[ "each", t => `util.forEach(${t.slice(4).trim()},($value,$key)=>{` ],
[ "each", t => `util.forEach(${t.slice(4).trim()},(value,key)=>{` ], // own valuename {{each items ->|as|=> item}}
[ "/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()}"];`],
[ "=", t => `html+=${t.slice(1).trim()};` ]
];
forEach(o, f) {
@ -16,7 +18,7 @@ export default new class {
else
throw new Error(`${o} is not a iterable object`);
}
render(tpl, data) {
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++)
@ -25,6 +27,6 @@ export default new class {
return `html+='${t}';`;
})
.join`` + "}return html.trim().replace(/>[\\n\\r\\s]*?</g, '><')")
.bind(null, { forEach: this.forEach })(data);
.bind(null, { forEach: this.forEach, snippets: this.snippets })(data);
}
};