Handlebars.js Else If
Asked Answered
D

8

291

I'm using Handlebars.js for client side view rendering. If Else works great but I've encountered a 3 way conditional that requires ELSE IF:

This doesn't work:

{{#if FriendStatus.IsFriend }}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else if FriendStatus.FriendRequested}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}

How do I do ELSE IF with handlebars?

Durman answered 24/5, 2012 at 11:48 Comment(1)
Keep an eye to the handlebars updates, seems it will be implemented soon: github.com/wycats/handlebars.js/pull/892Ungracious
B
455

Handlebars supports {{else if}} blocks as of 3.0.0.

Handlebars v3.0.0 or greater:

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else if FriendStatus.FriendRequested}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}

Prior to Handlebars v3.0.0, however, you will have to either define a helper that handles the branching logic or nest if statements manually:

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
  {{#if FriendStatus.FriendRequested}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
  {{else}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
  {{/if}}
{{/if}}
Bleeder answered 4/6, 2012 at 15:40 Comment(6)
is the point in not having an elsif (or else if) in handlebars that you are putting too much logic into your template. In other words, you need to break it down into smaller templates?Glim
@KazimZaidi, what if you have a single piece of data with more than three states which requires different formatting in each case? You may be able to force a CSS style into the data itself, but then you're pushing view-level concerns into your data. I can imagine sensible cases for an if/elseif/endif construct (or even a switch/match).Millepede
looking at this again, I feel this can be done through attribute bindings.Glim
I think the preferred method is to pass boolean flags and conditionalize them. Its up to you to set the flags properly such that only the one condition evaluates to true. No need for else ifRank
I'd recommend that you do this with a helper function to separate your business logic from presentation.Convenance
how to check if string is empty if var_is_empty <print this> else <print that>Russophobe
A
79

I usually use this form:

{{#if FriendStatus.IsFriend}}
  ...
{{else}} {{#if FriendStatus.FriendRequested}}
  ...
{{else}}
  ...
{{/if}}{{/if}}
Archeozoic answered 23/10, 2013 at 7:53 Comment(3)
Good tip, thanks. Would this be reactive by default?Nestorius
Looks pretty with only 1 else if, but the more you have, the longer that last list of closing if's gets - {{/if}}{{/if}}{{/if}}{{/if}}{{/if}}Blood
No, it's not "cleaner" it's uglier.Exieexigency
B
42

Handlebars now supports {{else if}} as of 3.0.0. Therefore, your code should now work.

You can see an example under "conditionals" (slightly revised here with an added {{else}}:

    {{#if isActive}}
      <img src="star.gif" alt="Active">
    {{else if isInactive}}
      <img src="cry.gif" alt="Inactive">
    {{else}}
      <img src="default.gif" alt="default">
    {{/if}}

http://handlebarsjs.com/block_helpers.html

Baseless answered 6/5, 2015 at 16:28 Comment(4)
doesn't work for me (syntax error in template). Meteor 1.2.0.2Blindfold
@Blindfold Which version of Handlebars is Meteor 1.2.0.2 using? Make sure you're using 3.0.Baseless
I'm using default version. How do I check handlebar version?Blindfold
@Blindfold It looks like Meteor uses its own template language called Spacebars. If that's the case, then I'm not sure it supports the {{else if}} syntax.Baseless
D
38

The spirit of handlebars is that it is "logicless". Sometimes this makes us feel like we are fighting with it, and sometimes we end up with ugly nested if/else logic. You could write a helper; many people augment handlebars with a "better" conditional operator or believe that it should be part of the core. I think, though, that instead of this,

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
  {{#if FriendStatus.FriendRequested}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
  {{else}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
  {{/if}}
{{/if}}

you might want to arrange things in your model so that you can have this,

{{#if is_friend }}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{/if}}

{{#if is_not_friend_yet }}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{/if}}

{{#if will_never_be_my_friend }}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}

Just make sure that only one of these flags is ever true. Chances are, if you are using this if/elsif/else in your view, you are probably using it somewhere else too, so these variables might not end up being superfluous.

Keep it lean.

Detrude answered 13/11, 2013 at 10:41 Comment(2)
I'm not sure how good of a practice it is, but this came up for me today handling 3 different view states and I ended up using a solution based off this (their elseif logic isn't necessary since they're all checking against one value) #15009064 So, instead of #if _is_friend, you can use a string with a very simple helper (in their answer); #if friend_type "is_friend" and #if friend_type "is_not_friend_yet"Boabdil
This answer is what I would consider the best solution pre handlebars 3.0, I think extra HTML is better as opposed to trying to cram logic into the DOM Tree.Ma
T
7

I wrote this simple helper:

Handlebars.registerHelper('conditions', function (options) {
    var data = this;
    data.__check_conditions = true;
    return options.fn(this);
});


Handlebars.registerHelper('next', function(conditional, options) {
  if(conditional && this.__check_conditions) {
      this.__check_conditions = false;
      return options.fn(this);
  } else {
      return options.inverse(this);
  }
});

It's something like Chain Of Responsibility pattern in Handlebars

Example:

    {{#conditions}}
        {{#next condition1}}
            Hello 1!!!
        {{/next}}
        {{#next condition2}}
            Hello 2!!!
        {{/next}}
        {{#next condition3}}
            Hello 3!!!
        {{/next}}
        {{#next condition4}}
            Hello 4!!!
        {{/next}}
    {{/conditions}}

It's not a else if but in some cases it may help you)

Twobit answered 14/8, 2015 at 12:21 Comment(0)
L
3

Built-in Helpers

#if

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

template

<div class="entry">
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

When you pass the following input to the above template

{
  author: true,
  firstName: "Yehuda",
  lastName: "Katz"
}
Legist answered 9/3, 2020 at 23:14 Comment(0)
P
1

in handlebars first register a function like below

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

you can register more than one function . to add another function just add like below

Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
    let result;
    switch (operator) {
        case '+':
            result = operand1 + operand2;            
            break;
        case '-':
            result = operand1 - operand2;            
            break;
        case '*':
            result = operand1 * operand2;            
            break;
        case '/':
            result = operand1 / operand2;            
            break;
    }

    return Number(result);
});

and in HTML page just include the conditions like

    {{#ifEquals day "mon"}}
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      //html code goes here
    </html>
   {{else ifEquals day "sun"}}
    <html>
     //html code goes here
    </html>
   {{else}}
     //html code goes here
   {{/ifEquals}}
Prosperous answered 11/9, 2020 at 15:36 Comment(0)
R
0

Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,

server.js

app.engine('handlebars', ViewEngine({
        "helpers":{
                isActive: (val, options)=>{
                    if (val === 3 || val === 0){
                        return options.fn(this)
                    }
                } 
        }
}));

header.handlebars

<ul class="navlist">
          <li   class="navitem navlink {{#isActive 0}}active{{/isActive}}"
                ><a href="#">Home</a></li>
          <li   class="navitem navlink {{#isActive 1}}active{{/isActive}}"
                ><a href="#">Trending</a></li>
          <li   class="navitem navlink {{#isActive 2}}active{{/isActive}}"
                ><a href="#">People</a></li>
          <li   class="navitem navlink {{#isActive 3}}active{{/isActive}}"
                ><a href="#">Mystery</a></li>
          <li class="navitem navbar-search">
            <input type="text" id="navbar-search-input" placeholder="Search...">
            <button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
          </li>
        </ul>
Raymond answered 3/6, 2020 at 3:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.