Search code examples
loopsember.jshandlebars.jseach

each with index and modulo in ember and handlebar


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}}

Solution

  • 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>