Handlebars template for Ember.js objects grouped b

2019-08-02 20:29发布

问题:

I have my data in the collection and I need to render them into the template. How can I achieve the result when the data is grouped by two? I need to sort them like this:

._______________________
| 1 | 3 | 5
|___|___|_______________
| 2 | 4 | and so on...
|___|___|_______________

I have created vertical div element for each 1+2, 3+4, ... pair to style the items like this. How can I render the data in to such grid with handlebars? All I can do is this:

{{#each App.myController}}
 ... render item ...
{{/each}}

回答1:

Firstly, i'd attempt to do this in CSS if at all possible in your layout.

If not, your best bet would to add a computed property to your controller that groups them into pairs and do it that way. Something like this:

{{#each App.myController.pairedContent}}
  <!-- view for content.firstObject -->
  <!-- view for content.lastObject -->
{{/each}}

App.MyController = Ember.ArrayController.extend({
  pairedContent: ( function(){
    return this.get('content').reduce( function(array, object, index){
      if(index % 2){
        array.get('lastObject').pushObject(object)
      }
      else{
        array.pushObject(Ember.A([object]))
      }
      return array
    }, Ember.A())
  }).property('content')
})