lessless
lessless

Reputation: 896

How to wrap each pair in the div inside {{#each}} loop

Question is how to wrap every two subsequent items inside {{#each}} loop in a div to get this layout

<ul>
  <div>
    <li>first item</li>
    <li> second item</li>
  </div>
  <div>
    <li>third item</li>
    <li> fourth item</li>
  </div>
  // etc...
</ul>

for that model

[
  {id: 1, name: 'first item'},
  {id: 2, name: 'second item'},
  {id: 3, name: 'third item'},
  {id: 4, name: 'fourth item'},
  // etc...
]

Upvotes: 0

Views: 118

Answers (1)

Karim Baaba
Karim Baaba

Reputation: 259

I don't think there is a straight up way to do this using the {{#each}} helper.

Here's what I would do...

1.

Write a custom template helper ( starting with {{#each}} )

2. Re-model the Array

 model: function() {
      var arr = [
            {id: 1, name: 'first item'},
            {id: 2, name: 'second item'},
            {id: 3, name: 'third item'},
            {id: 4, name: 'fourth item'},
            // etc...
      ];
      // splits array in pairs of 2
      return _.chunk(arr, 2); 
 }

_.chunk is a lodash helper but you can easily roll your own implementation.

Template:

 <ul>
 {{#each model as |pair|}}
      <li>{{pair.firstObject}}</li>
      <li>{{pair.lastObjectObject}}</li>
 {{/each}
 </ul>

.firstObject and .lastObject are Ember.Array helpers. If you have EXTEND_PROTOTYPES disabled you can do the following instead:

 <ul>
 {{#each model as |pair|}}
      {{#each pair as |item|}}
           <li>{{item}}</li>
      {{/each}
 {{/each}
 </ul>

Upvotes: 1

Related Questions