| 472 | |
| 473 | var cache = {}; |
| 474 | function tmpl(str, data){ |
| 475 | // Figure out if we're getting a template, or if we need to |
| 476 | // load the template - and be sure to cache the result. |
| 477 | var fn = !/\W/.test(str) ? |
| 478 | cache[str] = cache[str] : |
| 479 | |
| 480 | // Generate a reusable function that will serve as a template |
| 481 | // generator (and which will be cached). |
| 482 | new Function("obj", |
| 483 | "var p=[],print=function(){p.push.apply(p,arguments);};" + |
| 484 | |
| 485 | // Introduce the data as local variables using with(){} |
| 486 | "with(obj){p.push('" + |
| 487 | |
| 488 | // Convert the template into pure JavaScript |
| 489 | str |
| 490 | .replace(/[\r\t\n]/g, " ") |
| 491 | .split("<%").join("\t") |
| 492 | .replace(/((^|%>)[^\t]*)'/g, "$1\r") |
| 493 | .replace(/\t=(.*?)%>/g, "',$1,'") |
| 494 | .split("\t").join("');") |
| 495 | .split("%>").join("p.push('") |
| 496 | .split("\r").join("\\'") + |
| 497 | "');}return p.join('');" |
| 498 | ); |
| 499 | |
| 500 | // Provide some basic currying to the user |
| 501 | return data ? fn( data ) : fn; |
| 502 | } |
| 503 | return tmpl(templateString,valuesObject); |
| 504 | }, |
| 505 | /* jshint ignore:end */ |