1 // Simple JavaScript Templating
  2 // John Resig - http://ejohn.org/ - MIT Licensed
  3 (function(){
  4   var cache = {};
  5   
  6   this.tmpl = function tmpl(str, data){
  7     // Figure out if we're getting a template, or if we need to
  8     // load the template - and be sure to cache the result.
  9     var fn = !/\W/.test(str) ?
 10       cache[str] = cache[str] ||
 11         tmpl(document.getElementById(str).innerHTML) :
 12       
 13       // Generate a reusable function that will serve as a template
 14       // generator (and which will be cached).
 15       new Function("obj",
 16         "var p=[],print=function(){p.push.apply(p,arguments);};" +
 17         
 18         // Introduce the data as local variables using with(){}
 19         "with(obj){p.push('" +
 20         
 21         // Convert the template into pure JavaScript
 22         str
 23           .replace(/[\r\t\n]/g, " ")
 24           .split("<%").join("\t")
 25           .replace(/((^|%>)[^\t]*)'/g, "$1\r")
 26           .replace(/\t=(.*?)%>/g, "',$1,'")
 27           .split("\t").join("');")
 28           .split("%>").join("p.push('")
 29           .split("\r").join("\\'")
 30       + "');}return p.join('');");
 31     
 32     // Provide some basic currying to the user
 33     return data ? fn( data ) : fn;
 34   };
 35 })();