Skip to content

Instantly share code, notes, and snippets.

@gf3
Created Jun 12, 2009
Embed
What would you like to do?
Render JS string templates
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.
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