1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type content="text/html; charset=utf-8"> 5 <title>with-進入到某個屬性(進入到某個上下文環境) - by 楊元</title> 6 </head> 7 <body> 8 <h1>with-進入到某個屬性(進入到某個上下文環境)</h1> 9 <!--基礎html框架--> 10 <table> 11 <thead> 12 <tr> 13 <th>姓名</th> 14 <th>性別</th> 15 <th>年齡</th> 16 <th>興趣愛好</th> 17 </tr> 18 </thead> 19 <tbody id="tableList"> 20 21 </tbody> 22 </table> 23 24 <!--插件引用--> 25 <script type="text/javascript" src="script/jquery.js"></script> 26 <script type="text/javascript" src="script/handlebars-1.0.0.beta.6.js"></script> 27 28 <!--Handlebars.js模版--> 29 <!--Handlebars.js模版放在script標籤中,保留了html原有層次結構,模版中要寫一些操作語句--> 30 <!--id可以用來唯一確定一個模版,type是模版固定的寫法--> 31 <script id="table-template" type="text/x-handlebars-template"> 32 {{#each this}} 33 <tr> 34 <td>{{name}}</td> 35 <td>{{sex}}</td> 36 <td>{{age}}</td> 37 <td> 38 {{#with favorite}} 39 {{#each this}} 40 <p>{{name}}</p> 41 {{/each}} 42 {{/with}} 43 </td> 44 </tr> 45 {{/each}} 46 </script> 47 48 <!--進行數據處理、html構造--> 49 <script type="text/javascript"> 50 $(document).ready(function() { 51 //模擬的json對象 52 var data = [ 53 { 54 "name": "張三", 55 "sex": "0", 56 "age": 18, 57 "favorite": 58 [ 59 { 60 "name":"唱歌" 61 },{ 62 "name":"籃球" 63 } 64 ] 65 }, 66 { 67 "name": "李四", 68 "sex": "0", 69 "age": 22, 70 "favorite": 71 [ 72 { 73 "name":"上網" 74 },{ 75 "name":"足球" 76 } 77 ] 78 }, 79 { 80 "name": "妞妞", 81 "sex": "1", 82 "age": 18, 83 "favorite": 84 [ 85 { 86 "name":"電影" 87 },{ 88 "name":"旅遊" 89 } 90 ] 91 } 92 ]; 93 94 //註冊一個Handlebars模版,通過id找到某一個模版,獲取模版的html框架 95 //$("#table-template").html()是jquery的語法,不懂的童鞋請惡補。。。 96 var myTemplate = Handlebars.compile($("#table-template").html()); 97 98 //將json對象用剛剛註冊的Handlebars模版封裝,得到最終的html,插入到基礎table中。 99 $('#tableList').html(myTemplate(data)); 100 }); 101 </script> 102 </body>
103 </html>
注:在循環每名學生時,學生的favorite屬性並不是一個普通的字符串,而又是一個json對象,確切的說是一個list,我們需要把學生的愛好全部取出來。
這時候就需要with命令,這個命令可以讓當前的上下文進入到一個屬性中,{{#with favorite}}表示進入到favorite屬性的上下文中,而favorite屬性中又是一個list,因此可以用{{#each this}}進行遍歷,表示遍歷當前上下文環境,對於每次遍歷,都是map結構,取name屬性,最終拿到所有興趣愛好。