Content can be conditionally rendered using {#if} blocks, which allow you to show or hide markup based on expressions.
Basic If Block
The simplest form renders content only when a condition is true:
Example
If-Else Blocks
Add an {:else} clause for content to show when the condition is false:
Example
Else-If Chains
Test multiple conditions with {:else if} clauses:
Example
Real-World Use Cases
Inline Conditionals
Blocks don’t have to wrap elements - they can wrap text within elements:
Nested If Blocks
You can nest if blocks for complex conditions:
Common Patterns
Show/Hide Toggle
Empty State
Status Indicators
Avoid too many nested if blocks as they can make templates hard to read. Consider extracting complex logic into separate components or computed values.
Svelte efficiently updates the DOM when conditions change:
- Only the affected parts of the DOM are updated
- Elements inside false conditions are removed from the DOM
- When conditions become true, elements are created fresh