Check if an item is in array for Handlebars

VM Vera Mazhuga Vera Mazhuga

Vera Mazhuga

Software Developer
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>

Written by Vera Mazhuga

VM Vera Mazhuga Vera Mazhuga

Vera specializes in writing and maintaining code for various applications. Her focus on problem-solving and efficient programming ensures reliable and effective software solutions.

Newsletter

Subscribe to our newsletter:

Read more

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

1 min read.

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

1 min read.

Build Once. Own Forever.