|
|
|
|
|
by sharkbrainguy
5050 days ago
|
|
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"
}
}));
|
|