Sub topic 9
Rules for writing a valid chain
This chapter covers the rules that decide whether a chain of lwc:if, lwc:elseif, and lwc:else compiles and renders as you expect. It assumes you can write an LWC template and a JavaScript class, bind properties with curly braces, and write getters. It also assumes you have already used a single lwc:if. The goal here is to know the rules well enough to predict compiler errors before you see them.
What a chain is
A chain is a group of directives that the compiler treats as one block. The block starts with lwc:if, can continue with any number of lwc:elseif branches, and can end with one lwc:else. At runtime, LWC tests the conditions from top to bottom. It renders the first branch whose condition is truthy and skips the rest. If no condition is truthy and an lwc:else exists, the lwc:else branch renders.
Because the branches are linked, the chain evaluates each condition at most once per render. The legacy if:true and if:false pair can't do this. It tests the same property in two separate places.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
</template>
<template lwc:else>
<p>Data is ready.</p>
</template>
</template>Exactly one of the three paragraphs is in the DOM at any time. If isLoading and hasError are both true, only the loading paragraph renders, because the first truthy branch wins.
Rule 1: Start with lwc:if
An lwc:elseif or lwc:else has no meaning on its own. It must follow an element or template that carries lwc:if or lwc:elseif. If you place one at the start of a group, or after an unrelated element, the compiler reports an error.
<template>
<!-- Invalid: nothing before this lwc:else starts a chain -->
<p lwc:else>Fallback</p>
</template>Think of it the same way as else in JavaScript. You can't write else without a preceding if.
Rule 2: Branches must be adjacent siblings
Each lwc:elseif and lwc:else must be the next element sibling of the previous branch. They must share the same parent. Nothing else may sit between two branches, and a branch can't be moved into a different parent.
<template>
<!-- Invalid: a paragraph interrupts the chain -->
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<p>Always visible</p>
<template lwc:else>
<p>Done</p>
</template>
</template>The paragraph in the middle breaks the link, so the lwc:else has no lwc:if to attach to. Move the paragraph above or below the whole chain.
Whitespace and HTML comments between branches are fine. They are not elements, so they don't break adjacency. The earlier legacy-versus-new comparison in this tutorial uses this: the <!-- Equivalent with lwc:if and lwc:else --> comment sits before a chain, not inside one, but you can place comments between branches when you want to explain them.
Rule 3: lwc:else takes no value
lwc:if and lwc:elseif each need an expression in curly braces. lwc:else is the opposite. It is a bare attribute with no value, because it means "everything the earlier conditions did not match".
<template>
<p lwc:if={hasItems}>You have {itemCount} items.</p>
<p lwc:else>Your list is empty.</p>
</template>Writing lwc:else={something} is a compile error. If you need a condition on the final branch, use lwc:elseif instead.
Rule 4: Conditions are simple references
The expression in lwc:if and lwc:elseif must be a property reference such as {isLoading} or {state.isOpen}. It can't be a JavaScript expression. These are all invalid:
<template>
<!-- Invalid: negation, comparison, and calls are not allowed -->
<p lwc:if={!isLoading}>Ready</p>
<p lwc:if={status === 'error'}>Error</p>
<p lwc:if={items.length > 0}>Has items</p>
</template>Move the logic into a getter, as the chapter on getters showed.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
items = [];
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
get hasItems() {
return this.items.length > 0;
}
get isEmpty() {
return !this.hasItems;
}
}A getter such as isEmpty covers the negation case. In a chain you rarely need it, because lwc:else already covers the opposite of hasItems.
Rule 5: A chain has one lwc:else, and it comes last
You can have as many lwc:elseif branches as you need, but only one lwc:else, and it must be the final branch. Nothing may follow it in the chain. A second lwc:else, or an lwc:elseif after an lwc:else, is an error.
| Pattern | Valid? | Reason |
|---|---|---|
| `if` then `else` | Yes | The basic two-branch form. |
| `if`, `elseif`, `elseif`, `else` | Yes | Any number of `elseif` branches. |
| `if` then `elseif` with no `else` | Yes | The `else` is optional. |
| `elseif` first | No | No chain was started. |
| `if`, `else`, `elseif` | No | Nothing can follow `else`. |
| `if`, `else`, `else` | No | Only one `else`. |
| `else` with a value | No | `lwc:else` takes no value. |
Rule 6: Don't mix directive families
The new directives and the legacy if:true and if:false directives can't be mixed on the same element, and they don't link to each other. An lwc:else after an if:true block is not a valid chain. Use one family in each block. Prefer the lwc: family in new code, and see the migration chapter for converting old templates.
Rule 7: One conditional directive per element
An element can carry only one of lwc:if, lwc:elseif, or lwc:else. If you need both a condition and a second condition on the same content, nest the blocks instead (the next chapters cover nesting), or combine the logic in a getter.
Putting the rules together
The following diagram shows how LWC walks a chain. It stops at the first branch that matches.
Here is a longer chain that follows all the rules. It uses a getter for each condition, several lwc:elseif branches, and a final lwc:else.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
<button onclick={handleRetry}>Retry</button>
</template>
<template lwc:elseif={isEmpty}>
<p>No records found.</p>
</template>
<template lwc:else>
<p>{itemCount} records loaded.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class RecordPanel extends LightningElement {
status = 'loading';
items = [];
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
get isEmpty() {
return this.status === 'ready' && this.items.length === 0;
}
get itemCount() {
return this.items.length;
}
handleRetry() {
this.status = 'loading';
}
}Order matters here. If status is 'error', isEmpty is false because it also checks for 'ready'. Without that check, an errored component with an empty list would satisfy both hasError and isEmpty, and only the earlier branch would show. The chain would still behave correctly, but you would be relying on position instead of on clear conditions. Making each getter state its own case is easier to read and safer to reorder.
Truthiness inside a chain
Each condition follows the usual JavaScript rules. false, 0, '', null, undefined, and NaN are falsy. Everything else is truthy, including the string 'false', the number -1, and empty arrays and objects. An empty array is truthy, so lwc:if={items} renders its branch even when items is empty. Use a getter that checks length instead.
Checking your own templates
When a chain fails to compile or doesn't render as you expect, check these in order:
- Does the chain start with
lwc:if? - Are all branches adjacent siblings with the same parent?
- Does every
lwc:ifandlwc:elseifhave a plain property reference, and doeslwc:elsehave no value? - Is
lwc:elselast, and is there only one? - Are the old
if:trueandif:falsedirectives absent from the chain?
Exercise
A template has <template lwc:if={isOpen}>, then a <p> with a note, then <template lwc:else>. The compiler rejects it. Why, and how do you fix it without removing the note?
Show answer
The <p> sits between the lwc:if and the lwc:else, so the two are no longer adjacent siblings and the lwc:else has no chain to join. Move the <p> above the lwc:if block or below the lwc:else block. If the note should appear only in one branch, put it inside that branch's template.
Exercise
You need a chain that shows "Admin tools" when isAdmin is true, "Editor tools" when isEditor is true, and "Read only" otherwise. Write the template and say which directive takes no value.
Show answer
Use <template lwc:if={isAdmin}><p>Admin tools</p></template>, then <template lwc:elseif={isEditor}><p>Editor tools</p></template>, then <template lwc:else><p>Read only</p></template>, all as adjacent siblings. The lwc:else directive takes no value. If a user is both admin and editor, only "Admin tools" shows, because the first truthy branch wins.