這篇文章主要介紹了一個JavaScript微型模版,需要的朋友可以參考下
我一直在使用一個小工具,并發(fā)現(xiàn)它在構(gòu)建Javascript應用過程中非常實用。它是一個非常簡單的模板函數(shù),速度快,支持緩存,并容易使用。我想分享一下使用它的過程中的一些技巧。
以下是模板函數(shù)的代碼(你可以從正要出版的Secrets of the JavaScript Ninja一書中得到更精煉的版本):
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // 簡單JavaScript模板引擎 // John Resig - http://ejohn.org/ - MIT Licensed (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // 判斷我們是否已經(jīng)有這么一個模板,或者我們需要載入模板 // 并保證把結(jié)果保存到緩存中。 var fn = !/W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // 生成一個可重用的函數(shù),用于提供模板生成功能 // (它會被記錄到緩存內(nèi)). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // 通過with(){}把數(shù)據(jù)作為本地變量引入 "with(obj){p.push('" + // 把模板轉(zhuǎn)換未純javascript代碼 str .replace(/[rtn]/g, " ") .split("<%").join("t") .replace(/((^|%>)[^t]*)'/g, "$1r") .replace(/t=(.*?)%>/g, "',$1,'") .split("t").join("');") .split("%>").join("p.push('") .split("r").join("'") + "');}return p.join('');"); // 給用戶提供一些基本的柯里化功能 return data ? fn( data ) : fn; }; })();你的模板代碼看起來將是類似于(這并不是規(guī)定的格式,但是我比較喜歡這樣):
?
1 2 3 4 5 6 7 8 9 10 <script type="text/html" id="item_tmpl"> <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>"> <div class="grid_1 alpha right"> <img class="righted" src="<%=profile_image_url%>"/> </div> <div class="grid_6 omega contents"> <p><b><a href="/<%=from_user%>"><%=from_user%></a>:新聞熱點
疑難解答