Added app.template fill method to automatically expand variables in template

This commit is contained in:
Niko 2022-02-14 00:53:51 +01:00
parent 12f3b4c9cc
commit 1c646d0528
2 changed files with 41 additions and 17 deletions

View File

@ -7,19 +7,37 @@ app.script = function(name, cback) {
loadScript(name, file, cback);
}
app.template = function(name, cback) {
if (window.__cache_templates === undefined)
window.__cache_templates = {};
file = app.vars.js_dir + '/templates/' +
name.replaceAll('.', '/') + '.html';
name = 'template__'+name.replaceAll('.', '-');
if (window.__cache_templates[name] !== undefined)
return cback(window.__cache_templates[name]);
http.get(file, {}, function(html) {
html = html.trim();
window.__cache_templates[name] = html;
return cback(html);
});
app.template = {
load: function(name, cback) {
if (window.__cache_templates === undefined)
window.__cache_templates = {};
file = app.vars.js_dir + '/templates/' +
name.replaceAll('.', '/') + '.html';
name = 'template__'+name.replaceAll('.', '-');
if (window.__cache_templates[name] !== undefined)
return cback(window.__cache_templates[name]);
http.get(file, {}, function(html) {
html = html.trim();
window.__cache_templates[name] = html;
return cback(html);
});
},
fill: function(data, tpl) {
const res = Array.from(tpl.matchAll(/\{\.[^\{\}]+\}/g));
var matches = [];
for (var i = 0; i < res.length; i++) {
const m = res[i][0];
matches.push(m.replace(/^\{\./, '')
.replace(/\}$/, ''));
}
for (var i = 0; i < matches.length; i++) {
const k = matches[0];
if (k.match(/^[a-zA-Z0-9_\.]+$/))
tpl = tpl.replaceAll('{.'+k+'}',
eval(`data.${k}`));
}
return tpl;
},
}
function scriptPageHandler(modname, cfg) {
@ -33,10 +51,12 @@ function scriptPageHandler(modname, cfg) {
}
window.onload = function(e) {
scriptPageHandler('pages.home', { exact: '' });
scriptPageHandler('pages.meet', { exact: 'meet' });
scriptPageHandler('pages.crushes', { exact: 'crushes' });
scriptPageHandler('pages.chat', { exact: 'chat' });
if (getNormalizedURI() === app.vars.app_dir) {
scriptPageHandler('pages.home', { exact: '' });
scriptPageHandler('pages.meet', { exact: 'meet' });
scriptPageHandler('pages.crushes', { exact: 'crushes' });
scriptPageHandler('pages.chat', { exact: 'chat' });
}
window.onhashchange();
}

View File

@ -29,6 +29,10 @@ function loadScript(id, file, cback) {
document.body.appendChild(script);
}
function getNormalizedURI() {
return window.location.pathname.replace(/\/+?$/, '');
}
function JSON_to_URLEncoded(element,key,list) {
var list = list || [];
if (typeof(element) == 'object') {