Underscore [18] : 使用 template 樣板

摘要:Underscore 使用 template 樣板引擎

今天來介紹 Underscore 的樣板引擎 , 其使用了 _.template 的關鍵字  , 

 

在使用之前我們得知道為啥使用樣板引擎 ? 它解決了啥問題 ? 

 

我們常會獲得如 JSON , XML  這樣的資料來源 , 而我們需要將這些資料展示在 HTML , 

 

所以我們得在 JS 裡面寫好混合 html 和 資料的東西 , 然後一起返回 ,

 

而樣板引擎通常賦予我們分離資料與 html 的能力 , 這也是目前其他 JS framework 都有的功能 ,

 

其目的就是為了解決這個問題 ,

 

我們底下的範例會讓資料直接繫結表格 , 

 

首先來定義我們的資料部份 : 

 


var items = [
    {name:"Holmes2136"},
    {name:"Sherlock"},
    {name:"Conan"},
    {name:"Doyle"}
];

 

定義我們的樣板 : 


<script type="text/html" id='table-data'>
    
    <% _.each(items,function(item,key,list){ %>
        <tr>
            <td><%= key %></td>
            <td><%= item.name %></td>
        </tr>
    <% }) %>

</script>

 

取得樣板的資料 : 

 


var tableTemplate = $("#table-data").html();

 

讓表格繫結資料來源 : 

 


$("table.outer tbody").html(_.template(tableTemplate,{items:items}));

 

如果我們刪除了某筆資料 , 那 html 會變化嗎 ? 

 

Underscore 並非具有 Angular 的雙向繫結能力 , 所以你需要重新繫結 : 

 

先來刪除掉 item 最後一筆資料 : 

 


items.pop()

 

重新繫結 : 

 


$("table.outer tbody").html(_.template(tableTemplate,{items:items}));

 

程式範例 : 

JS Bin