Blog
Check if an item is in array for Handlebars
 Vera Mazhuga
        
    
    Vera Mazhuga
Vera Mazhuga
Software DeveloperHow 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
 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.
Scale your company with the same people
Practical ideas to do more and get back your time every week
We respect your inbox. Privacy policy
 
        
    
    
