2012-11-23 39 views
0

這裏是我的代碼如何在text/html中的下劃線模板中包含數據源?

<script type="text/html" id='usageList'> 
      <table cellspacing='0' cellpadding='0' border='1' > 
       <thead> 
        <tr> 
         <th>Id</th> 
         <th>Name</th> 
         <th>LastName</th> 
        </tr> 
       </thead> 

       <tbody> 
        /* I want to include data source via ajax or some mechanism here */ 
        <%_.each(items,function(item,key,list){ %> 
        <% var f = item.name; %><!-- create more variables --> 
        <% var l= item.lastName; %> 
        <tr> 
         <!-- use variables --> 
         <td><%= key %></td> 
         <td class="<%= f %>"><%= f %></td> 
         <td class="<%= l %>"><%= l %></td> 
        </tr> 
        <% }); %> 
       </tbody> 
      </table> 
     </script> 

回答

1

首先,讓模板到一個變量

var template = ​$(​'#usageList')​​​​​​​​​​​​​​.html(); 

然後,讓一個Ajax請求。使用_.template過程中接收到的數據,並把它添加到DOM節點

$.getJSON('ajax/test.json', function(data) { 
    $('#output').html(_.template(template,{items:data})); 
}); 

返回的數據必須遵循此格式

[ 
    {'name':'john', 'lastName':'M'}, 
    {'name':'jean', 'lastName':'N'}, 
    {'name':'carl', 'lastName':'K'}, 
    {'name':'peter', 'lastName':'B'} 
] 

入住此的jsfiddle:http://jsfiddle.net/jaimem/2gPYZ/