2020-08-01 21:51:54 +02:00
|
|
|
class Template {
|
|
|
|
constructor() {
|
|
|
|
this.tpl = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
async loadTemplate(name) {
|
|
|
|
let self = this;
|
|
|
|
if (!this.tpl[name]) {
|
|
|
|
await fetch(templateDir + name + ".tpl").then((r) => r.text()).then(c => {
|
|
|
|
self.tpl[name] = c;
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async loadArray(names) {
|
|
|
|
for (let name of names) {
|
|
|
|
await this.loadTemplate(name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
parseTemplate(name, data) {
|
|
|
|
if (!this.tpl[name]) {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
let m, d = this.tpl[name];
|
|
|
|
while ((m = templateEx.exec(d)) !== null) {
|
|
|
|
if (m.index === templateEx.lastIndex) {
|
|
|
|
templateEx.lastIndex++;
|
|
|
|
}
|
|
|
|
let key = m[0];
|
2020-08-06 23:44:37 +02:00
|
|
|
let value = data[m[1]];
|
|
|
|
if (value === undefined || value === null) {
|
|
|
|
value = "";
|
|
|
|
}
|
|
|
|
d = d.replace(key, value)
|
2020-08-01 21:51:54 +02:00
|
|
|
}
|
|
|
|
return d;
|
|
|
|
}
|
|
|
|
|
|
|
|
parseFromAPI(url, name, cb) {
|
|
|
|
fetch(url).then((r) => r.json()).then(d => {
|
|
|
|
cb(this.parseTemplate(name, d))
|
|
|
|
}).catch(console.error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const templateEx = /\$(.*?)\$/gm;
|
|
|
|
const templateDir = "out/tpl/"
|