2013-06-05 21 views
0

我嘗試ember.js/handlebars.js在第一時間內填充細胞,儘管它是非常簡單的,我有我想不出一個簡單的用例。如何使用handlebars.js到行

數據如下:

var columns = ['col2', 'col3'], 
    rows = [{ 
    col1: 1, 
    col2: 2, 
    col3: 3 }, 
    { 
    col1: 11, 
    col2: 12, 
    col3: 13 } 
    ]; 

我怎樣才能創建一個可生成一個模板:

<table> 
<tr><td>2</td><td>3</td></tr> 
<tr><td>12</td><td>13</td></tr> 
</table> 
換句話說

,所顯示的細胞都是基於columns陣列?

回答

3

因爲它似乎要選擇顯示的列,首先將你的rows/columns成一個陣列所需的特定行:

table: function() { 
    var table, 
     newRow, 
     columns = this.get('columns'), 
     rows = this.get('rows'); 

    table = []; 
    rows.forEach(function(rowItem, rowIndex, rowEnumerable){ 
     newRow = []; 
     columns.forEach(function(colItem, colIndex, colEnumerable){ 
     if (rowItem[colItem] !== undefined) { 
      newRow.pushObject(rowItem[colItem]); 
     } 
     }); 
     table.pushObject(newRow); 
    }); 

    return table; 
    }.property('[email protected]', '[email protected]') 

這是一個computed property是將包含行數組的數組:

[ 
    [2,3], 
    [12,13] 
] 

然後可以使用把手{{#each ... }} helpers遍歷每一行和每一行中使用另一個{{#each ...}}幫手迭代在每個單元:

<table> 
    {{log table}} 
    {{#each row in table}} 
    <tr> 
     {{#each cell in row}} 
     <td>{{cell}}</td> 
     {{/each}} 
    </tr> 
    {{/each}} 
</table> 

JSBin example

+0

啊!所以比我預期的要複雜一點。 –

+0

Right @Jack,我覺得Ember可以 –

0

也許這是不完整的解決方案,但作爲一個出發點,你可以去了解它是這樣的:

在模板:

<table> 
    {{#each row in model.rows}} 
    <tr> 
     {{#each col in model.columns}} 
     <td>{{row}}</td> 
     {{/each}} 
    </tr> 
    {{/each}} 
</table> 

而在你的路線提供數據:

App.IndexRoute = Ember.Route.extend({ 
    model: function(){ 
    return Ember.Object.create({ 
     columns: ['col1', 'col2'], 
     rows: [1, 2, 3, 11, 12, 13] 
    }); 
    } 
}); 

這裏工作jsbin

希望它可以幫助