Skip to main content

Part 1 / Logic / If blocks

HTML doesn't have a way of expressing logic, like conditionals and loops. Svelte does.

To conditionally render some markup, we wrap it in an if block:

App.svelte
{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{/if}

{#if !user.loggedIn}
	<button on:click={toggle}>
		Log in
	</button>
{/if}

Try it — update the component, and click on the buttons.

Next: Else blocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
	let user = { loggedIn: false };
 
	function toggle() {
		user.loggedIn = !user.loggedIn;
	}
</script>
 
<button on:click={toggle}>
	Log out
</button>
 
<button on:click={toggle}>
	Log in
</button>
 
initialising