8
votes

I have a controller with data about user accounts (icon, name, provider, etc.). Within the output of the each loop I have a view that will build a CSS class dynamically based on the provider passed in via that specific model.

<script type="text/x-handlebars" data-template-name="accountItem">
{{#each account in controller}}
    {{#view App.AccountView}}
        <h4>{{account.name}}</h3>
        <img {{bindAttr src="account.icon"}} />
        <i {{bindAttr class="account.provider"}}></i>
    {{/view}}
{{/each}}
</script>

App.AccountView = Ember.View.extend({
    tagName: 'a',
    classNames: ['avatar-image'],
    providerClass: function(el) {
        // do something
    }
});

The question I have is two-fold.

  1. How do you pass in "account", or the currently iterated item, into the view?
  2. After you pass it in, how do you reference it?

I'm sure this is something that happens quite often but I can't seem to find any examples. Can anyone offer some input on this please?

2

2 Answers

11
votes

Views has a special content property in a view which allows a more simple approach: you just use a name of the model's property without the view.content. part.
Also, when you're iterating over controller, you can omit the name of loop variable and use this instead, like in this guide. This is not necessary but can make the code a bit cleaner.
Also, from within view's template you generally don't need to reference the outside variables although you can if you like..

{{#each controller}}
    {{#view App.IndexView contentBinding="this"}}
        <h4>{{name}}</h4>
        <img {{bindAttr src="icon"}} />
        <i {{bindAttr class="provider"}}></i>
        <i> {{icon}} </i>
        <i>{{provider}}</i>
    {{/view}}
{{/each}}

And you can always access the content property from within the view with:

this.get('content');
2
votes

The currently iterated item can be passed into the view with the help of property bindings and it can be refered as "{{view.property}}" in the template. For example:

{{#each account in controller}}
     {{#view App.IndexView itemBinding="account"}}
            <h4>{{view.item.name}}</h3>
            <img {{bindAttr src="account.icon"}} />
            <i {{bindAttr class="account.provider"}}></i>
              <i> {{view.item.icon}} </i>
              <i>{{view.item.provider}}</i>
        {{/view}}
{{/each}} 

I have created a simple jsfiddle for the above case. Do check it and let me know if you were able to resolve the issues.

Fiddle url : http://jsfiddle.net/nCyn6/3/