2016-03-11 118 views
0

我試圖從數組中生成兩個表。Handlebars js,獲取特定的對象數組並循環遍歷

"tables": [ 
{ 
"tableName": "table1", 
"dataRow": ["name": "test858"] 
}, 
{ 
"tableName": "table2", 
"anotherRow": ["name": "test123"] 
} 
] 

我試着這樣做

{{#each tables}} 
      <table> 
       <thead> 
        <tr> 
         <th>{{tableName}}</th> 
         <th></th> 
        </tr> 
       </thead> 
       <tbody> 
        <tr> 
         {{#if dataRow}} 
         <td>test1</td> 
         {{else}} 
         <td>test2</td> 
         {{/if}} 
        </tr> 
       </tbody> 
      </table> 
{{/each}} 

此打印兩個表名和 「測試2」

我如何遍歷兩個陣列?

回答

0

工作示例JSFiddle

var entry_template = document.getElementById('entry-template').innerHTML; 
var tables = [ 
{ 
"tableName": "table1", 
"dataRow": [{"name": "test858"}] 
}, 
{ 
"tableName": "table2", 
"anotherRow": [{"name": "test123"}] 
} 
]; 

var template = Handlebars.compile(entry_template); 
var template_with_data = template(tables); 

document.getElementById('data').insertAdjacentHTML('afterbegin', template_with_data); 

模板:

<script id="entry-template" type="text/x-handlebars-template"> 
{{#each this}} 
      <table> 
       <thead> 
        <tr> 
         <th>{{tableName}}</th> 
         <th></th> 
        </tr> 
       </thead> 
       <tbody> 
        <tr> 
         {{#if dataRow}} 
         <td>test1</td> 
         {{else}} 
         <td>test2</td> 
         {{/if}} 
        </tr> 
       </tbody> 
      </table> 
{{/each}} 
</script> 
<div id="data"> 
</div>