How to Use {:else} in Svelte: Simple If-Else Blocks Explained
In Svelte, use
{#if condition} to show content when a condition is true, and {:else} to show alternative content when it is false. The {:else} block must directly follow the {#if} block without any other code or whitespace in between. This creates a clean, readable way to handle two possible UI states.Syntax
The {#if} block checks a condition. If true, it shows the content inside it. The {:else} block runs only if the condition is false. Both blocks must be together without anything between them.
{#if condition}: Start the if block with a condition.- Content inside if block: Shown if condition is true.
{:else}: Start the else block.- Content inside else block: Shown if condition is false.
{/if}: Ends the if-else block.
svelte
{#if condition}
<!-- content if true -->
{:else}
<!-- content if false -->
{/if}Example
This example shows a simple message that changes based on a boolean variable loggedIn. If loggedIn is true, it shows a welcome message. Otherwise, it shows a prompt to log in.
svelte
<script> let loggedIn = false; </script> {#if loggedIn} <p>Welcome back, user!</p> {:else} <p>Please log in to continue.</p> {/if} <button on:click={() => loggedIn = !loggedIn}> Toggle Login State </button>
Output
Please log in to continue.
[Toggle Login State button]
Common Pitfalls
One common mistake is placing any code or whitespace between the {#if} and {:else} blocks, which breaks the syntax. Another is forgetting to close the block with {/if}. Also, {:else} must always follow an {#if} block; it cannot be used alone.
svelte
<!-- Wrong: code between if and else --> {#if condition} <p>True</p> <p>Extra line</p> {:else} <p>False</p> {/if} <!-- Right: no extra code between --> {#if condition} <p>True</p> {:else} <p>False</p> {/if}
Quick Reference
Remember these tips when using {:else} in Svelte:
- Always pair
{:else}directly after{#if}. - Close the block with
{/if}. - Use
{:else if}for multiple conditions. - Keep the blocks clean without extra code between.
Key Takeaways
Use
{:else} immediately after {#if} to show alternative content.Never put extra code or whitespace between
{#if} and {:else} blocks.Always close your conditional blocks with
{/if}.{:else} cannot be used alone; it must follow an {#if} block.For multiple conditions, use
{:else if} instead of multiple {:else}.