使用underscore.js 和 template 來刻網頁。
摘要:藉由underscore.js 以及 template 來取代以往的組Html字串。
以往小弟在做網頁的時候,往往會有利用Ajax得到資料後來Render網頁的時候。
這時候的做法,通常都是在Ajax success的時候開始【刻】起了字串。
例如:
<script type="text/script">
var html='';
$.ajax({
url:url,
type:type,
dataType:dataType,
data:data,
success:function(json){
html='<div>'+json+'</div>';
}
});
</script>
當構築的網頁不會太大太複雜的時候,慢慢刻總會完成。
但是當要構築的網頁落落長且重複利用率很高的時候.....就會有點麻煩,而且也不是這麼好維護。
然後經過同事的開示!!~ 認識了一下underscore & Template 。發現其實真的滿方便的 !
基本上是參考
(Underscore.js 是個Javascript Library,其功能不單單只有使用template,但本篇只在嘗試underscore與template之間的關係,所以其他的功能就...等我這個小菜鳥慢慢地研究後出來再紀錄吧!)
2. Ruoyu Sun's When You Need to Render Large DOM in Underscore.js
簡單的來說就是先建立好Html Template樣板,然後在需要Render 網頁的時候,將Data變數載入樣板,然後一起Load出來,就有一個完整的Html!
用法大概就像以下:
1.建立個Html。
("_"是underscore.js的物件。obj是建立template物件時,未指定傳入的物件名稱,則名稱Default為obj。詳細請參考Underscore.js原始網站)
<script type='text/template' id='testTemplate'>
_.each(obj,function(index,value){
<div><%=value%></div>
});
</script>
2. 利用get 去取得template的Dom
<script type='text/script'>
$.get(template's_Url,function(htmlDom){
template=_.template(htmlDom)
});
</script>
3. 將Data丟到剛剛建立的template物件中,然後取得完整的Html
<script type='text/script'>
html=template(Data);
</script>
這是將Html Dom獨立出去,利用Get來載入樣板的方法。
如果只是單純在某個頁面使用,也可以直接在網頁中建立<script type='text/template' id='testTemplate'>,然後很簡單的利用jQuery來取得Dom。
但是這時候就要注意underscore.js 的templateSetting是否會和原網頁規則有衝突。
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
我碰到的情況是在asp中<%%>是asp的程式碼片段,此時就要去修改templateSetting啦!~
參考連結
Ruoyu Sun's When You Need to Render Large DOM in Underscore.js
http://stackoverflow.com/questions/15624922/underscore-interpolate-settings