Sureshkumar Natarajan
Sureshkumar Natarajan

Reputation: 538

emberjs nested {{#each}} not working

i am very new to ember js.

i am trying to form a data grid in my page.

modal

{
"tableView":{
    "columns":[{"name":"EmpName","datatype":"string"},{"name":"Age","datatype":"numeric"}],
    "records":[{"EmpName":"Ramesh","Age":12},{"EmpName":"Mukesh","Age":31},{"EmpName":"Mahesh","Age":22}]
    }
}

template

<script type="text/x-handlebars" data-template-name="grid">
<table>
<thead>
<tr>
    {{#each tableView.columns}}
    <th>    {{name}}</th>
    {{/each}}
</tr>
</thead>
<tbody>
{{#each record in tableView.records}}
<tr>
 {{#each column in tableView.columns}}
    <td>{{record[column.name]}}</td>
 {{/each}}
</tr>
{{/each}}
</tbody>
</table>
</script>

In result, the table header with the columns is showing correctly. but the data is not generated in the table and no error.

am i doing anything wrong in the inner {{#each}}??

Upvotes: 2

Views: 1211

Answers (1)

melc
melc

Reputation: 11671

To render the table with records you try something like,

http://emberjs.jsbin.com/nahanoje/1/edit

hbs

<table>
<thead>
<tr>
    {{#each model.tableView.columns}}
    <th>    {{name}}</th>
    {{/each}}
</tr>
</thead>
<tbody>
{{#each record in model.tableView.records}}
<tr>
    <td>{{record.EmpName}}</td>
    <td>{{record.Age}}</td>
</tr>
{{/each}}
</tbody>
</table>

In the original code posted the {{record[column.name]}} part will not work.

If you need to have a nested {{each}} helper to get dynamically the values of an arbitrary number of columns, then a registered helper for this specific task will really assist.

http://emberjs.jsbin.com/foqohibe/1/edit

js

App.IndexRoute = Ember.Route.extend({
  model: function() {

    var data = {
"tableView":{
    "columns":[{"name":"EmpName","datatype":"string"},{"name":"Age","datatype":"numeric"}],
    "records":[{"EmpName":"Ramesh","Age":12},{"EmpName":"Mukesh","Age":31},{"EmpName":"Mahesh","Age":22}]
    }
};

    return data;
  }
});

Ember.Handlebars.helper('getRecord', function(value, options) {
  var record = arguments[0];
  var columnName = arguments[1];
  return new Handlebars.SafeString(record[columnName]);
});

hbs

    <table>
<thead>
<tr>
    {{#each model.tableView.columns}}
    <th>    {{name}}</th>
    {{/each}}
</tr>
</thead>
<tbody>
{{#each record in model.tableView.records}}
<tr>
{{#each column in model.tableView.columns}}
{{#with column}}
<td>{{getRecord record name}}</td>
{{/with}}
{{/each}}    
</tr>
{{/each}}
</tbody>
</table>

Upvotes: 2

Related Questions