Search code examples
htmlember.jshandlebars.js

Ember.js {{#each}} value in html tag?


So I am using Ember.js each helper and I am having trouble putting values where I want them.

Here is what I want my html to look like.

<div id="item0">
  item0Value
</div>

But I can't figure out how to write this in the handlebars template.

This is what I tried.

{{#each item in array}}
  <div id="item{{item.id}}">
    {{item.value}}
  </div>
{{/each}}

This gives me an error.

Uncaught Error: Assertion Failed: An error occured while setting up template bindings. Please check for invalid markup or bindings within HTML comments.

Is there a way to do what I want here? or is it not possible to put values inside the html tags?


Solution

  • From ember/guides:

    It is often useful to specify a controller to decorate individual items in the ArrayController while iterating over them. This can be done by creating an ObjectController:

    You can use an item controller to generate the values you need, and then access them in your template:

    {{#each item in array itemController="song"}}
      <div {{bind-attr="item.cssId"}}>
        {{item.value}}
      </div>
    {{/each}}
    
    // controllers/song
    App.SongController = Ember.ObjectController.extend({
       cssId: function() {
         return 'item' + this.get('id');
       }.property('id')
    ...
    

    Note: As best practice it is better to declare your itemController in the template, and not directly in your ArrayController