1
votes

I've setup a simple handlebars template displays images from records from a model. The following works as expected and uses the imageURL on each item to display the image.

{{#each this}}

<img {{bindAttr src="imageURL"}} >

{{/each}}

However, I also want to display the first image in the set of records. Going by How do I access an access array item by index in handlebars? I added the following with no luck.

<img {{bindAttr src="this.0.imageURL"}} >

I also tried the following with no luck either.

{{#with this.[0]}}
<img {{bindAttr src="imageURL"}} >
{{/with}}

Any ideas?

Notables: Ember 1.2.0, Handlebars 1.2.0, jQuery 1.10.2

3

3 Answers

0
votes

The reason that this doesn't work is because this refers to the ArrayController that rendered this template. Now you're probably wondering why {{#each this}} works. That's because Ember will get the content property of the array controller, which is an Ember.Array containing the actual image objects.

Please read this documentation on Ember.ArrayController: http://emberjs.com/api/classes/Ember.ArrayController.html.

In order to display the first image you could extend your controller like so:

App.IndexController = Ember.ArrayController.extend({
  firstImage: function() {
    this.get('firstObject');
  }.property('[]')
});

You'll have to use this.get('firstObject') since Ember.Array works a bit different than a normal js array. Here you'll find some more documentation: http://emberjs.com/api/classes/Ember.Array.html#property_firstObject.

Displaying the first image in your template becomes easy now:

<img {{bindAttr src="firstImage.imageURL"}} />
0
votes

It seems to work:

Template:

<script type="text/x-handlebars" data-template-name="index">
  <ul>
  {{#each this}}
    <img {{bindAttr src="this.0.imageURL"}} >
  {{/each}}
  </ul>
</script>

JS:

App = Ember.Application.create();

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
             [
               {imageURL: "http://placehold.it/100x100"},
               {imageURL: "http://placekitten.com/200/200"}
             ], 
             [
               {imageURL: "http://placehold.it/200x200"},
               {imageURL: "http://placekitten.com/100/100"}
             ],
             [
               {imageURL: "http://placehold.it/300x300"},
               {imageURL: "http://placekitten.com/300/300"}
             ]
           ];
  }
});

JSBin example

0
votes

If you go to Try Handlebars.js and add to Handlebars Template {{this.0.img}} and to Context (JavaScript literal or JSON)

[{
   img: 'path/to/img'
}, {
   img: 'path/to/img'
}]

Its work. Maybe problem in your helper.