4 ms·
function render(tpl,data){ var matches = tpl.match(/{[^\}]+}/g); for(var i in matches){ var rep = eval("data."+matches[i].replace('{','').replace('}
by vain 14y ago
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 http://pastebin.com/txM6NZBS here, to copy and paste
- alexgartrell 14y agorender("{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
- vain 14y agolooks like something broke in copying and pasting. try: http://pastebin.com/txM6NZBS http://pastebin.com/txM6NZBS
- deleted 14y ago[deleted]
- pfraze 14y agofunction 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
- jasonmoo 14y agoI like it. Here's a slightly more stable version. But still not crazy about using eval on arbitrary code. O.O function render(tpl,data){ return tpl.replace(/{([^\}]+)}/g,function(_, key) { try { return eval("data."+key); } catch (e) { return ""; } }); }
- vain 14y agothe code i use in production doesn't use eval, but a recursive function. i like the anonymous function passed to replace, but think the catch destroys code beauty :)
- sharkbrainguy 14y agoYou can achieve the same effect without using eval, which his many known problems in terms of security and performance. 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" } }));