Created
June 1, 2016 14:34
-
-
Save marcteys/bea3bcb592b1757c10710155cec63762 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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