forked from f0ck/f0ckv2
.
This commit is contained in:
30
src/inc/tpl.mjs
Normal file
30
src/inc/tpl.mjs
Normal 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);
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user