Skip to main content Link Search Menu Expand Document (external link)

else : Fallback Branch Helper


On this page

Summary

Provides a fallback branch when conditional expressions are false or when collections are empty.

Based on: <otherwise> element in conditionals, or fallback content in iteration contexts

Syntax

With :


  <!-- Content when true -->

  <!-- Content when false -->

With :


  <!-- Content for each item -->

  <!-- Content when collection is empty -->

With :


  <!-- Content when object exists -->

  <!-- Content when object is null -->


Parameters

No parameters. The `` helper is used as a separator within block helpers.


Examples

With If Statement


  <button class="btn-primary">Add to Cart</button>

  <button class="btn-disabled" disabled>Out of Stock</button>

Data:

doc.Params["model"] = new {
    hasStock = false
};

Output:

<button class="btn-disabled" disabled>Out of Stock</button>

With Each Loop (Empty Collection)

<ul>

  <li></li>

  <li class="empty">No items available</li>

</ul>

Data:

doc.Params["model"] = new {
    items = new object[] { }  // Empty array
};

Output:

<ul>
  <li class="empty">No items available</li>
</ul>

With Context Switch (Null Object)


  <div class="user-profile">
    <h2></h2>
    <p></p>
  </div>

  <div class="no-profile">
    <p>User profile not available</p>
  </div>

Data:

doc.Params["model"] = new {
    user = (object)null
};

Output:

<div class="no-profile">
  <p>User profile not available</p>
</div>

Multiple Else If with Final Else


  <span class="a">A - Excellent</span>

  <span class="b">B - Good</span>

  <span class="c">C - Average</span>

  <span class="f">F - Needs Improvement</span>


Underlying Implementation

In blocks, `` compiles to:

<choose>
  <when data-test="">
    <!-- If content -->
  </when>
  <otherwise>
    <!-- Else content -->
  </otherwise>
</choose>

In blocks, `` creates a conditional wrapper:

<template data-bind="">
  <!-- Each content -->
</template>
<template data-test="count() == 0">
  <!-- Else content shown when empty -->
</template>

Notes

  • Can be used with ,, and ``
  • Only one block allowed per helper (use for multiple conditions)
  • For ``, the else block renders when all conditions are false
  • For ``, the else block renders when the collection is empty
  • For ``, the else block renders when the object is null or undefined
  • Position matters: must come after all `` blocks

See Also