Created
June 12, 2009 14:57
-
-
Save gf3/128678 to your computer and use it in GitHub Desktop.
Render JS string templates
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 data = { | |
business: { | |
id: 123, | |
service: "Cleaners", | |
name: "Weeoo", | |
user: { | |
id: 987, | |
name: "Jeff Smith" | |
} | |
} | |
}; | |
var template = "{business['user']['name']}'s business: {business['name']}, {business['service']}."; | |
var output = render(template, data); // John Smith's business: Weeoo, Cleaners. |
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 render(string, data) { | |
var regex = /{[\w\[\]']+?}/mig, //' | |
sub_regex = /\[[\w']+?\]/i; | |
return string.replace(regex, function(pattern, index) { | |
var name = pattern.replace(/({|})/g, ''); | |
try { | |
if (sub_regex.test(name)) { // Build object from string | |
var match_key = /\['([\w]+?)'\]/ig, | |
keys = [], | |
builder = data[name.match(/\w+/)[0]], // Get base object | |
match; | |
while (match = match_key.exec(name)) keys.push(match[1]); // Get object keys | |
for (var i=0; i<keys.length; i++) builder = builder[keys[i]]; // Build object from keys | |
return builder; | |
} | |
else return data[name].toString(); // Simply just a key, no need to build object | |
} | |
catch (e) { | |
throw(new Error('Cannot find template variable: {'+name+'}.')); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment