何爲模板引擎?從mustache到handlebars、jquery的模板插件jquery.tmpl、以及我廠的etpl~事實上模板引擎的實現原理並不複雜,可是寫一個對開發者友好且性能較高的模板引擎並不容易。but,各個模板引擎的性能高低以及好壞不在討論的範疇(若是你對此有強烈的興趣,請參看《深刻淺出nodeJS》一書的第八章相關的模板部分分析,固然你也能夠參看下面的一篇博客,高性能Javascript模板引擎原理分析),理解模板引擎的實現原理,從John Resig的Micro-template入手,相關博客爲Javascript Micro-Templating。javascript
直接看代碼java
// Simple JavaScript Templating // John Resig - http://ejohn.org/ - MIT Licensed (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){}, 動態執行 javascript 字符串,with改變做用域,訪問到data "with(obj){p.push('" + // Convert the template into pure JavaScript str .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('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; // test console.log(this.tmpl('<h1><%=text1 %></h1><h2><%=text2 %></h2>', {text1: 'text1 hello', text2: 'text2 hello'})); })();