Last active
November 13, 2015 02:26
-
-
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
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
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