handlebars-----if的基本用法

1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <META http-equiv=Content-Type content="text/html; charset=utf-8">
 5     <title>if-判斷的基本用法 - by 楊元</title>
 6   </head>
 7   <body>
 8     <h1>if-判斷的基本用法</h1>
 9     <!--基礎html框架-->
10     <table>
11       <thead>
12         <tr>
13           <th>姓名</th>
14           <th>性別</th>
15           <th>年齡</th>
16         </tr>
17       </thead>
18       <tbody id="tableList">
19         
20       </tbody>
21     </table>
22     
23     <!--插件引用-->
24     <script type="text/javascript" src="script/jquery.js"></script>
25     <script type="text/javascript" src="script/handlebars-1.0.0.beta.6.js"></script>
26     
27     <!--Handlebars.js模版-->
28     <!--Handlebars.js模版放在script標籤中,保留了html原有層次結構,模版中要寫一些操作語句-->
29     <!--id可以用來唯一確定一個模版,type是模版固定的寫法-->
30     <script id="table-template" type="text/x-handlebars-template">
31       {{#each student}}
32         {{#if name}}
33           <tr>
34             <td>{{name}}</td>
35             <td>{{sex}}</td>
36             <td>{{age}}</td>
37           </tr>
38         {{/if}}
39       {{/each}}
40     </script>
41     
42     <!--進行數據處理、html構造-->
43     <script type="text/javascript">
44       $(document).ready(function() {
45         //模擬的json對象
46         var data = {
47                     "student": [
48                         {
49                             "name": "張三",
50                             "sex": "0",
51                             "age": 18
52                         },
53                         {
54                             "sex": "0",
55                             "age": 22
56                         },
57                         {
58                             "name": "妞妞",
59                             "sex": "1",
60                             "age": 18
61                         }
62                     ]
63                 };
64         
65         //註冊一個Handlebars模版,通過id找到某一個模版,獲取模版的html框架
66         //$("#table-template").html()是jquery的語法,不懂的童鞋請惡補。。。
67         var myTemplate = Handlebars.compile($("#table-template").html());
68         
69         //將json對象用剛剛註冊的Handlebars模版封裝,得到最終的html,插入到基礎table中。
70         $('#tableList').html(myTemplate(data));
71       });
72     </script>
73   </body>

74 </html>

注:在遍歷student時,由於數據缺失,並不是每一個學生都有name屬性,我們不想顯示沒有name屬性的學生,這時就需要if來做判斷。

     {{#if name}}可以用來判斷當前上下文中有沒有name屬性,實際上,它是嘗試去讀取name屬性,如果返回的爲undefined、null、""、[]、false任意一個,都會導致最終結果爲假。

     if還支持多層次讀取,例如:{{#if name.xxx}},這樣寫就假設name屬性是一個map,檢測name屬性中是否包含xxx屬性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章