1 (function(){ 2 var cache = {}; 3 4 this.tmpl = function tmpl(str, data){ 5 // Figure out if we're getting a template, or if we need to 6 // load the template - and be sure to cache the result. 7 var fn = !/\W/.test(str) ? 8 cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : 9 // Generate a reusable function that will serve as a template 10 // generator (and which will be cached). 11 new Function("obj", 12 "var p=[],print=function(){p.push.apply(p,arguments);};" + 13 // Introduce the data as local variables using with(){} 14 "with(obj){p.push('" + 15 // Convert the template into pure JavaScript 16 str 17 .replace(/[\r\t\n]/g, " ") 18 .split("<%").join("\t") 19 .replace(/((^|%>)[^\t]*)'/g, "$1\r") 20 .replace(/\t=(.*?)%>/g, "',$1,'") 21 .split("\t").join("');") 22 .split("%>").join("p.push('") 23 .split("\r").join("\\'") 24 + "');}return p.join('');"); 25 // Provide some basic currying to the user 26 return data ? fn( data ) : fn; 27 }; 28 })(); 29 30 assert( tmpl("Hello, <%= name %>!", {name: "world"}) == 31 "Hello, world!", "Do simple variable inclusion." ); 32 var hello = tmpl("Hello, <%= name %>!"); 33 assert( hello({name: "world"}) == "Hello, world!", 34 "Use a pre-compiled template." ); 35 }
36 /**动态生成的函数*/ 37 function(obj){ 38 var p=[],print=function(){p.push.apply(p,arguments);}; 39 with(obj){p.push(' 40 str 41 .replace(/[\r\t\n]/g, " ") 42 .split("<%").join("\t") 43 .replace(/((^|%>)[^\t]*)'/g, "$1\r") 44 .replace(/\t=(.*?)%>/g, "',$1,'") 45 .split("\t").join("');") 46 .split("%>").join("p.push('") 47 .split("\r").join("\\'") 48 '); 49 } 50 return p.join('');
<html> <head> <script type="text/tmpl" id="colors"> <p>Here's a list of <%= items.length %> items:</p> <ul> <% for (var i=0; i < items.length; i++) { %> <li style='color:<%= colors[i % colors.length] %>'> <%= items[i] %></li> <% } %> </ul> and here's another... </script> <script type="text/tmpl" id="colors2"> <p>Here's a list of <%= items.length %> items:</p> <ul> <% for (var i=0; i < items.length; i++) { print("<li style='color:", colors[i % colors.length], "'>", items[i], "</li>"); } %> </ul> </script> <script src="tmpl.js"></script> <script> var colorsArray = ['red', 'green', 'blue', 'orange']; var items = []; for ( var i = 0; i < 10000; i++ ) items.push( "test" ); function replaceContent(name) { document.getElementById('content').innerHTML = tmpl(name, {colors: colorsArray, items: items}); } </script> </head> <body> <input type="button" value="Run Colors" onclick="replaceContent('colors')"> <input type="button" value="Run Colors2" onclick="replaceContent('colors2')"> <p id="content"> Replaced Content will go here </p> </body> </html>