Handlebar if else helper examples| Conditional expression in handlebarJS

This tutorials covers an handlebar if help classes with examples, it also includes how to test conditional block execution in handlebar mustache templates.

HandlebarJS provides {{#if}} and {{#unless}}helper provides an helper to conditional test the expression against javascript objects.

if condition in handlebar helps to solve below things

  • Conditional to check an object is null or undefined or empty

if and unless are used to check properties of an object not an expressions

  id: 1,
  name: "john",
  salary: 5000,

Here is an html template to check for name is null or undefined or empty

<div class="printname">
{{#if name}}
<h1>{{name}} {{salary}}</h1>

This enables to render a block of code on condition is passed.

Please note that we have #if block followed by rendered block with end block.

if else helper in handlerbarJS

Handlebar support if and else conditional block to render html templates It uses if and else helper classes to achieve that

Some times, We want to execute block on re

<div class="printname">
{{#if name}}
<h1>{{name}} {{salary}}</h1>
<h1>No Employee found</h1>

if name is found, It executes block inside it otherwise it executes else block.

else if helper in handlerbarJS

Nested if inside else can be used in handlerbarJS from version 3.x.

Here is an syntax

{{#if isAdmin}}
{{else}} {{#if isHr}}

How to use if in for loop with handlebarjs

Some times, while iteration of an array of json object, We want to check conditional if expression.

Here is an example to check if inside for each iteration.


if helper checks each object name value found, if not else block is executed.

{{#each this}}
  {{#if this.name  }}
<div>Name Found </div> {{/if}}
  <div>There are no Roles.</div>


In this tutorial, You learned how to do conditional if else logic helper in javascript template examples with handlebarJS

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.