Reputation: 115
I have a handlebars template that looks like this:
<tr>
{{#each columns}}
<th>
{{name}}
</th>
{{/each}}
</tr>
{{#each items}}
<tr>
{{each columns}}
<td>
{{! I want the items statusString field here for example }}
{{../dataField}}
</td>
{{/each}}
</tr>
{{/each}}
and the input to this template looks a bit like this:
columns = [
{name: 'status', dataField: 'statusString'},
{name: 'name', dataField: 'name'}
]
items = [
{status: 1, statusString: 'Active', name: 'item 1'},
{status: 1, statusString: 'Active', name: 'item 2'},
{status: 0, statusString: 'Disabled', name: 'item 3'},
{status: 1, statusString: 'Active', name: 'item 4'}
]
in the template i want to iterate each column and display for each item the data that corresponds to each column. But how do I do it in handlebars? I've tried expressions like {{../{{dataField}}
, {{{{dataField}}}}
but I can't get anything to work.
I use handlebars in ember.js.
Upvotes: 4
Views: 1142
Reputation: 6099
This can be completed simply by using a helper
Handlebars.registerHelper('helper', function(fieldname, item) {
return item[fieldname];
});
Another way to do it would be using an object iterator, which has been recently added by handlebars. You can iterate through an object like this
var data = {"a": {"test":"test", "test2":"test2"}};
with a template
{{#each a}}
{{@key}} - {{this}},
{{/each}}
Would print out "test - test, test2 - test2,". If you edited your data you could get the correct output by using this.
Heres a jsfiddle showing both of these.
Upvotes: 3