Search code examples
node.jsexpressexpress-handlebars

Custom Express Handlebars If Helper


I'm iterating over an array object utilizing express-handlebars and only every second dom element which is created should have a specific attribute.

Something like this:

<div class=""></div>
<div></div>
<div class=""></div>
<div></div>

I noticed that there is a @size value which contains the index of the iteration.

My code so far is looking like this:

{{#each todoGroups}}
         {{#if @index}}
            <div class=""></div>
         {{/if}}
{{/each}}

But how do I add a condition to the if statement which only evaluates to true for every second item?

I'm stuck trying to implement this functionality this is my approach so far:

function hbsHelpers(hbs) {
  return hbs.create({
    helpers: { // This was missing
      isEven: function(value, options) {

      },

      // More helpers...
    },

  });
}

Solution

  • Handlebars is unfortunately quite bad at these things, and I think you need to do some custom helpers like the one you are doing.

    I would suggest writing your own block-helper that takes three arguments and performs the basic logical checks (like and, or, greater than, less than, modulus), something like:

    {{#ifCond varOne "%" 2}}
    {{/ifCond}}
    

    And the ifCond helper implementation has a switch case to handle different operators.