by vain · 14y ago · 0 comments
function render(tpl,data){
var matches = tpl.match(/{[^\}]+}/g);
for(var i in matches){
var rep = eval("data."+matches[i].replace('{','').replace('}',''));
tpl = tpl.replace(matches[i],rep);
}
return tpl;
}
alert(render("{a} is all that i've {b.a} {b.b} {b.c}", {a:"this", b:{a:"ever",b:"really",c:"needed"} }))
http://pastebin.com/txM6NZBS here, to copy and paste function render(tpl,data){
function lookup (obj, keys) {
return (keys.length === 0) ? obj
: lookup(obj[keys[0]], keys.slice(1));
}
var matches = tpl.match(/\{[^\}]+\}/g),
max = matches.length,
i, rep, keys;
for (i = 0; i < max; i++) {
keys = matches[i].slice(1, -1).split('.');
rep = lookup(data, keys);
tpl = tpl.replace(matches[i],rep);
}
return tpl;
}
alert(render("{a} is all that i've {b.a} {b.b} {b.c}", {
a: "this",
b: {
a: "ever",
b: "really",
c: "needed"
}
})); function render(tpl,data){
return tpl.replace(/{([^\}]+)}/g,function(_, key) {
try { return eval("data."+key); }
catch (e) { return ""; }
});
} render("{a} is all that I've {a}", {'a' : 'b'});
"b is all that I've b"
render("{a} is all that I've {{a}}", {'a' : 'b'});
SyntaxError: Unexpected token {
Seems Legit function render(tpl,data){
var matches = tpl.match(/{[^\}]+}/g);
for(var i in matches){
var rep = eval("data."+matches[i].replace(/[{}]/g,''));
tpl = tpl.replace(matches[i],rep);
}
return tpl;
}
Fixed