benihana21
benihana21

Reputation: 168

Ember.js - conditionally display template content based on current model item index

I have an Ember.js app that requires me to render content in groups of 6. For example, I have a model that contains 18 'activities.' I need to group the activities in sets of six, so I'll have three groupings of six each. I know I can't use non-boolean conditionals in Handlebars, so does anyone have an idea on how to best implement the following concept?

<script type="text/x-handlerbars" data-template-name="categories">
  {{#each activity in parentController.activity}}
    // For every sixth item, start a new grouping
    {{#if activity.index() % 6 == 0}}
      <div class="activityBlock">
         // Render views 1 - 6 the first time, 7 - 12 the second time, and 13 - 18 the third time
         {{view "activity"}}
      </div>
    {{/if}}
  {{/each}}
</script>

<script type="text/x-handlebars" data-template-name="activity">
   {{item.title}}
</script>

Upvotes: 1

Views: 363

Answers (1)

Kalman
Kalman

Reputation: 8121

Expanding on what @MatthewBlancarte said in the comments, you can do the following:

App.IndexController = Ember.ArrayController.extend({
  categorySlices: function(){
    var model = this.get('model')
    var slice1 = model.slice(0, 6);
    var slice2 = model.slice(6, 12);
    var slice3 = model.slice(12);

    return [slice1, slice2, slice3];
  }.property('model')
})

And then, your template might look like this:

<script type='text/x-handlebars' id='index'>
  {{#each slice in categorySlices}}
    {{#each item in slice}}
      {{ item }}<br>
    {{/each}}
    <p>
  {{/each}}
</script>

See a working solution here

Upvotes: 2

Related Questions