Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

  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


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"
            } 
        }));


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 ""; }
          });
     }


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 :)


  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


looks like something broke in copying and pasting. try: http://pastebin.com/txM6NZBS




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: