javascript / beginner
Snippet
Rendering Conditional UI Elements with Svelte If-Else Blocks
Svelte provides template-level conditional control flow using `{#if}` and `{:else}` blocks. When the referenced condition changes value, Svelte automatically mounts or unmounts the corresponding DOM elements.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>let isLoggedIn = false;function toggleLogin() {isLoggedIn = !isLoggedIn;}</script>{#if isLoggedIn}<p>Welcome back, user!</p><button on:click={toggleLogin}>Log Out</button>{:else}<p>Please log in to continue.</p><button on:click={toggleLogin}>Log In</button>{/if}
svelte
Breakdown
1
let isLoggedIn = false;
Declares a reactive boolean variable that tracks login status.
2
{#if isLoggedIn}
Opens a conditional template block that renders when isLoggedIn evaluates to true.
3
{:else}
Provides the fallback branch rendered when the condition evaluates to false.
4
{/if}
Closes the conditional template block.