Skip to content

Instantly share code, notes, and snippets.

@marcteys
Created June 1, 2016 14:34
Show Gist options
  • Save marcteys/bea3bcb592b1757c10710155cec63762 to your computer and use it in GitHub Desktop.
Save marcteys/bea3bcb592b1757c10710155cec63762 to your computer and use it in GitHub Desktop.
var Templates = {
templates:{},
loadTemplates:function (names, callback) {
var that = this;
var loadTemplate = function (index) {
var name = names[index];
var rawFile = new XMLHttpRequest();
rawFile.open("GET", './templates/' + name + '.html', true);
rawFile.onload = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
that.templates[name] = allText;
console.log('Template: Loading template: ' + name);
index++;
if (index < names.length) {
loadTemplate(index);
} else {
if(typeof callback !== "undefined") callback();
}
}
}
}
rawFile.send(null);
}
loadTemplate(0);
},
get:function (name, data) {
var htmlTemplate = this.templates[name];
// Inject template in {{}}
if(typeof data !== 'undefined') {
for(var key in data)
{
var attrName = key;
var attrValue = data[key];
if(typeof attrValue === 'string' || typeof attrValue === 'number')
{
var reg = new RegExp('\{\{\\s*'+attrName+'\\s*\}\}', 'g');
htmlTemplate = htmlTemplate.replace(reg, attrValue);
}
}
//Remove all unused {{}}
var reg = new RegExp('\{\{\\s*(.*)\\s*\}\}', 'g');
htmlTemplate = htmlTemplate.replace(reg, '');
}
return htmlTemplate;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment