(function ($) { $.fn.razor = function (data) { var render=$(this).data(‘razor‘); if (!render) { var html = $(this).html(); var isNewEngine = ‘‘.trim; if (isNewEngine) { render = new Function("data", "var p=‘‘;" + "p+=‘" + html.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)‘/g, "$1\r").replace(/\t=(.*?)%>/g, "‘;p+=$1;p+=‘").split("\t").join("‘;").split("%>").join("p+=‘").split("\r").join("\\‘") + "‘;return p;"); } else { render = new Function("data", "var p=[];" + "p.push(‘" + html.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)‘/g, "$1\r").replace(/\t=(.*?)%>/g, "‘,$1,‘").split("\t").join("‘);").split("%>").join("p.push(‘").split("\r").join("\\‘") + "‘);return p.join(‘‘);"); } $(this).data(‘razor‘, render); } return render(data); } })(jQuery);
demo:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Razor模板引擎</title> <script src="Scripts/StringExtension.js"></script> <script src="Scripts/jquery-1.10.2.min.js"></script> <script src="Scripts/micro-template.js"></script> <script id="tmpl1" type="text/template"> <ul> <% for(var i=0,j=data.length;i<j;i++){ var item=data[i];%> <li><%=item.Name%></li> <%}%> </ul> </script> <script id="tmpl2" type="text/template"> <table> <% for(var i=0,j=data.length;i<j;i++){ var item=data[i];%> <tr><td><%=item.Name%></td></tr> <%}%> </table> </script> <script type="text/javascript"> $(function () { var p = []; $(‘#tmpl1‘).razor(p); $(‘#tmpl2‘).razor(p); for (var i = 0; i < 10000; i++) { p.push({Name:‘xyz‘+i.toString().padLeft(‘0‘,4)}); } console.time(‘render1‘); $(‘#content1‘).html($(‘#tmpl1‘).razor(p)); console.timeEnd(‘render1‘); console.time(‘render2‘); $(‘#content2‘).html($(‘#tmpl2‘).razor(p)); console.timeEnd(‘render2‘); }); </script> </head> <body> <div id="content1"></div> <div id="content2"></div> </body> </html>
时间: 2024-10-20 04:24:41