Re:T.js - A tiny templating framework in ~400 bytes
by vain on Monday August 13, 2012 @07:36PM
(#4378698)
http://pastebin.com/txM6NZBS here, to copy and paste
[ Parent
| on HN ]
Re:T.js - A tiny templating framework in ~400 bytes
by sharkbrainguy on Monday August 13, 2012 @08:00PM
(#4378764)
You 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"
}
}));
Re:T.js - A tiny templating framework in ~400 bytes
by jasonmoo on Monday August 13, 2012 @07:57PM
(#4378754)
I 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 ""; }
});
}
Re:T.js - A tiny templating framework in ~400 bytes
by vain on Monday August 13, 2012 @08:04PM
(#4378775)
the 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 :)
Re:T.js - A tiny templating framework in ~400 bytes
by alexgartrell on Monday August 13, 2012 @07:41PM
(#4378710)
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
Re:T.js - A tiny templating framework in ~400 bytes
by pfraze on Monday August 13, 2012 @07:53PM
(#4378740)
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
Re:T.js - A tiny templating framework in ~400 bytes
by vain on Monday August 13, 2012 @07:49PM
(#4378727)
looks like something broke in copying and pasting. try:
http://pastebin.com/txM6NZBS