Insights

Check if an item is in array for Handlebars

Photo of the author: Vera Mazhuga

Vera Mazhuga

  •  

1 min read.

How to check if an array contains a certain item in Handlebars template.


Context (JavaScript literal or JSON):

{
    "favourites": [2, 3],
    "hobbies": [
        {
            "name": "playing football",
            "id": 1
        },
        {
            "name": "reading books",
            "id": 2
        },
        {
            "name": "programming in python",
            "id": 3
        },
        {
            "name": "jogging",
            "id": 4
        }
    ]
}


Handlebars Template:

<div>
  {{#each hobbies }}
      <div style="{{#ifIn id ../favourites }}color: red{{/ifIn}}">
          {{ name }}
      </div>
  {{/each}}
</div>


Register Helper function:

Handlebars.registerHelper('ifIn', function(elem, list, options) {
  if(list.indexOf(elem) > -1) {
    return options.fn(this);
  }
  return options.inverse(this);
});


As a result we get the following html:

<div>
    <div style="">
        playing football
    </div>
    <div style="color: red">
        reading books
    </div>
    <div style="color: red">
        programming in python
    </div>
    <div style="">
        jogging
    </div>
</div>

Learn more by receiving an email once a month.

Additional Insights

Switching Between Compass Versions

Compass is a great framework that helps us writing clean styles using Sass, creating sprites, using mixins and among other f...

Author Pablo Vallejo Pablo Vallejo

OSX infinite login issue

OSX is a Linux cousin, if you know about the command line, you can fix problems, your system shouldn't be a black box. &nbsp...

Photo of the author: Igor Támara Igor Támara