Renders one of two templates based on a condition.
<!-- With templates -->
<div if="user.isAdmin" then="adminPanel" else="userPanel"></div>
<!-- Inline content — keeps children if true, removes if false -->
<div if="user.isLoggedIn">
<p>Welcome back!</p>
</div>
<!-- Negation -->
<div if="!user.isLoggedIn" then="loginPrompt"></div>
<!-- Complex expressions -->
<div if="user.role === 'admin' && user.verified" then="adminTpl"></div>
<div if="cart.items.length > 0" then="cartTpl" else="emptyCartTpl"></div><div if="status === 'loading'" then="loadingTpl"></div>
<div else-if="status === 'error'" then="errorTpl"></div>
<div else-if="status === 'empty'" then="emptyTpl"></div>
<div else then="contentTpl"></div>Toggles display: none without adding/removing DOM elements. Better for frequently toggled elements.
<div show="user.isLoggedIn">Welcome!</div>
<div hide="user.isLoggedIn">Please log in.</div>
<button show="!editing" on:click="editing = true">Edit</button>
<button show="editing" on:click="editing = false">Save</button>if |
show |
|
|---|---|---|
| Mechanism | Adds/removes DOM elements | Toggles CSS display |
| Best for | Rarely toggled content | Frequently toggled content |
| Preserves state | No (re-creates) | Yes |
Render one of many templates based on a value.
<div get="/me" as="user">
<div switch="user.role">
<div case="'admin'" then="adminDashboard"></div>
<div case="'editor'" then="editorDashboard"></div>
<div case="'viewer'" then="viewerDashboard"></div>
<div default then="guestDashboard"></div>
</div>
</div><div switch="order.status">
<span case="'pending'" class="badge warn">⏳ Pending</span>
<span case="'shipped'" class="badge info">📦 Shipped</span>
<span case="'delivered'" class="badge ok">✅ Delivered</span>
<span case="'cancelled'" class="badge err">❌ Cancelled</span>
<span default class="badge">Unknown</span>
</div><div switch="user.role">
<div case="'admin','superadmin'" then="adminPanel"></div>
<div case="'editor','writer'" then="editorPanel"></div>
<div default then="viewerPanel"></div>
</div>Loop directives (foreach, each, for) support else="templateId" to reference a <template> for empty-state fallback. The template renders when the list is empty ([]) or null/undefined/non-array — e.g. API state before the first fetch:
<article foreach="item in items" else="noItems">
<h2 bind="item.title"></h2>
</article>
<template id="noItems">
<p>No items found.</p>
</template>Breaking change (v1.15): The sibling
elsepattern for loops has been removed. Useelse="templateId"on the loop element itself. See Loops for details.
- Loops —
foreachwithfilterfor conditional rendering, andelsefor empty lists - Dynamic Styling —
show/hidealternative viaclass-* - Templates — template-based conditional content with
then/else
Previous: State Management ← | Next: Loops →