Skip to content

Instantly share code, notes, and snippets.

@NXTaar
Last active November 13, 2015 02:26
Show Gist options
  • Save NXTaar/8f76cf831ffca69b25d9 to your computer and use it in GitHub Desktop.
Save NXTaar/8f76cf831ffca69b25d9 to your computer and use it in GitHub Desktop.
Can generate HTML from the string with variables as ${variableName}. The value for that variable should be in data[variableName] The properties of the [data] could be generated recursively with this function
function generateHTML(data, template) {
String.prototype.multiReplace = function (hash) {
var str = this, key;
for ( key in hash ) {
str = str.replace( new RegExp( key, 'g' ), hash[ key ] );
}
return str;
};
var result = "";
var hash = {};
var variables = template.match(/\$({[^}{]+})/g);
variables.forEach(function(it, i, arr) {
var value = arr[i].replace(/[^\w+]/g, "");
hash['\\$\\{'+value+'\\}'] = data[value] !== undefined ? data[value] : "";
});
result = template.multiReplace(hash);
delete String.prototype.multiReplace;
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment