axiacore

Blog

Check if an item is in array for Handlebars

Vera Mazhuga

Vera Mazhuga

Jul 25, 2014

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>
Get in the loop and learn more about building digital products:

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

Pablo Vallejo

Pablo Vallejo

Dependency Management In Django Using Bower

In today's web applications it's very common to use libraries and have several dependencies that are used in the front end of...

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

Igor Támara

Igor Támara

We build software solutions for business from idea to launch.

Let's Talk