Home > OS >  Handlebars if statement going to else statement when if statement is correct
Handlebars if statement going to else statement when if statement is correct

Time:04-19

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  id="{{this._id}}">
    <p> Start a new conversation </p>
  </div>
{{else}}
  <p>else statement</p>
  {{#each messages}}

    <div  id="{{this._id}}">

      <div >
          <img src={{user.profilePicture}} width="100"
            height="100"
            />
      </div>
      <div >
        <span >{{this.sender.firstName}} {{this.sender.lastName}}</span>
        <div >{{this.createdAt}}</div>
      </div>

      <div >
        <p >
          {{this.message}}
        </p>
      </div>
    </div>
  {{/each}}
{{/if}}

CodePudding user response:

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.

  • Related