1

In my controller I have a list of strings like this:

columns : ['name', 'description']

I want to filter what is displayed in the template based on this list:

        {{#each m in controller.model}}
            {{#each col in controller.columns}}
               <td>{{m[col]}}</td>
            {{/each}}
        {{/each}}

Of course {{m[col]}} is not valid code but you get the idea. How might I achieve this?

This code is generic so I have no way of telling what the columns array contains before hand.

jax
  • 37,735
  • 57
  • 182
  • 278

2 Answers2

1

You can create a bound helper as follows:

Ember.Handlebars.registerBoundHelper('dd', function(rowData, col) {
  return rowData[col];
});

Then, you can use it in your template as follows:

{{#each item in model}}
  <tr>
    {{#each col in columns}}
      <td> {{ dd item col }} </td>
    {{/each}}
  </tr>
{{/each}}

Working example on jsbin here

Kalman
  • 8,001
  • 1
  • 27
  • 45
  • If I use Ember.set() to change the value of one of the item properties then the change is not shown in the template because the item property does not get bound by your helper. How can I get this to work so that changing the data updates the template? – galatians Jun 05 '15 at 20:08
0

If you want the data bound to the template so that it updates when the data changes, use a small component as follows:

App.getPropertyComponent = Ember.Component.extend({
    tagName: '',

    value: function() {
        var model = this.get('model');
        var method = this.get('method');

        return model[method];

    }.property('model.{name,description}')
});

Notice that you have to manually specify each property you are binding to.

Component template:

{{value}}

Then, you can use it in your template as follows:

{{#each item in model}}
  <tr>
    {{#each col in columns}}
      <td>{{get-property model=item method=col}}</td>
    {{/each}}
  </tr>
{{/each}}
galatians
  • 738
  • 7
  • 12