7

I am trying to find a way to parse out differently depending array index as odd or even number

I was looking at this http://assemble.io/helpers/helpers-comparison.html and hope to find something like this:

{{#each array}}
{{#if_odd {{@index}}}}
    {{this}} is odd 
{{else}}
    {{this}} is even
{{/if_odd}}
{{/each}}

I don't really care about the syntax but hope my idea comes across. Any help? Thanks.

HP.
  • 19,226
  • 53
  • 154
  • 253
  • 1
    Write your own `is_odd` helper and then `{{#is_odd @index}}` should work. Do you know anything about writing helpers? Have you done any research on writing your own helpers? – mu is too short Sep 24 '13 at 19:31
  • Yeah, I guessed using `{{#if_odd {{@index}}}}` is wrong and `{{#if_odd @index}}` is correct. No wonder why I couldn't get it to work originally. – HP. Sep 24 '13 at 22:28
  • Check out my own helper implementation for meteor 1.3+, http://stackoverflow.com/a/39175773/2305243 This is intened for Meteor developers only. – Alan Dong Aug 26 '16 at 23:10

1 Answers1

26

I created this helper and it worked

Handlebars.registerHelper('if_even', function(conditional, options) {
  if((conditional % 2) == 0) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

Just followed conditional helper here http://handlebarsjs.com/block_helpers.html

I tried to do this based on mu is too short suggestion:

{{#if_even @index}}
HP.
  • 19,226
  • 53
  • 154
  • 253