Search code examples
javascriptexpressmongoosehandlebars.js

Handlebars if statement going to else statement when if statement is correct


I am currently trying to write an if else block in handlebars for a messaging part of my social media app. I am passing through messages from the controller and for the example I am using, there is an empty array but for some reason it keeps going to the else statement. I have tried a number of different combinations for this to work but it keeps going to the else statement. What am I doing wrong?

{{#if messages.length}}
  <p>if statement</p>
  <div class="message-container card" id="{{this._id}}">
    <p> Start a new conversation </p>
  </div>
{{else}}
  <p>else statement</p>
  {{#each messages}}

    <div class="message-container card" id="{{this._id}}">

      <div class="profile-picture">
          <img src={{user.profilePicture}} width="100"
            height="100"
            class="rounded-circle"/>
      </div>
      <div class="message-header">
        <span class="name">{{this.sender.firstName}} {{this.sender.lastName}}</span>
        <div class="date-sent">{{this.createdAt}}</div>
      </div>

      <div class="post-body">
        <p class="message">
          {{this.message}}
        </p>
      </div>
    </div>
  {{/each}}
{{/if}}

Solution

  • Yes. That's correct. If there is an empty array it should go to the else statement because an empty array will have length of 0 which is falsy.

    In your code you have

    {{#if messages.length}}
        print this if array is not empty because
        message.length is not zero
    {{#else}}
        print this if array is empty
        because message.length is zero
    {{/if}}
    

    So it is behaving correctly.

    If you intend to do the opposite either swap the code inside the if and else blocks or replace #if with #unless.