Comment

Comment by sharkbrainguy

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"
            } 
        }));
parent sharkbrainguy 14 years ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton