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