7

I'm creating a slide - so there's 3 images every one div like so

<div>
  <img />
  <img />
  <img />
</div>

</div>
  <img />
  <img />
  <img />
</div>

None of the code around the internet works flawlessly -

https://github.com/johanpoirier/resthub-backbone-stack/commit/8a318477d56c370d2a0af4da6eae9999c7bb29da

http://jaketrent.com/post/every-nth-item-in-handlebars-loop/

http://rockycode.com/blog/handlebars-loop-index/

http://www.arlocarreon.com/blog/javascript/handlebars-js-everyother-helper/

and yes including the answers here in stack overflow.

Can anyone provide some code that works perfectly at this current period (version of Ember/Handlebar)?

I have an array of models so i'd like to do something like

{{#each model}}
    {{if index % 3 == 0}}
    {{/if}}
{{/each}}
David
  • 4,235
  • 12
  • 44
  • 52
  • Have you looked at http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional/9405113#9405113 there're quite a few examples to write custom conditions helpers. Also *index* is available via `@index` – colymba Aug 05 '13 at 12:35

2 Answers2

16

I have been finding that index or @index do not work from within the template, but you can access it from within a helper.

I've made an example here that demonstrates this:

http://jsbin.com/egoyay/1/edit

Edit: Adding code to answer, demonstrating {{else}} block

Handlebars helper (for non-Ember use):

Handlebars.registerHelper('ifIsNthItem', function(options) {
  var index = options.data.index + 1,
      nth = options.hash.nth;

  if (index % nth === 0) 
    return options.fn(this);
  else
    return options.inverse(this);
});

Usage:

<ol>
 {{#each model}}
   <li>
     {{#ifIsNthItem nth=3}}
        Index is a multiple of 3
     {{else}}
        Index is NOT a multiple of 3
     {{/ifIsNthItem}}
   </li>
 {{/each}}
</ol>
Paul
  • 19,704
  • 14
  • 78
  • 96
Kieran Hayes
  • 203
  • 2
  • 7
  • 1
    Nice. I found that `options.data.view.contentIndex` was not available, but accessing the index via `options.data.index` worked. – kontur Jan 02 '14 at 15:21
  • This worked great. How would you do the same thing, but with the ability to add an else into the mix? `{{ifIsNthItem nth=3}} do this {{else}} do something else {{/ifIsNthItem}}` – carter Oct 05 '14 at 19:37
2

If you specify itemViewClass in each helper, then it will create a view for each item and set contentIndex property:

{{#each model itemViewClass="Ember.View"}}
    {{view.contentIndex}}
{{/each}} 

tested in Ember v1.1.0

Champ
  • 1,291
  • 4
  • 16
  • 32
ladoch
  • 106
  • 4
  • 1
    Without specifying the itemViewClass, we can use _view.contentIndex. But that does not work inside a #if helper within the #each. – Champ Jun 02 '14 at 06:13