Since the two conditions — if user.loggedIn
and if !user.loggedIn
— are mutually exclusive, we can simplify this component slightly by using an else
block:
{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{:else}
<button on:click={toggle}>
Log in
</button>
{/if}
A
#
character always indicates a block opening tag. A/
character always indicates a block closing tag. A:
character, as in{:else}
, indicates a block continuation tag. Don't worry — you've already learned almost all the syntax Svelte adds to HTML.
App.svelte
xxxxxxxxxx
19
1
<script>
2
let user = { loggedIn: false };
3
4
function toggle() {
5
user.loggedIn = !user.loggedIn;
6
}
7
</script>
8
9
{#if user.loggedIn}
10
<button on:click={toggle}>
11
Log out
12
</button>
13
{/if}
14
15
{#if !user.loggedIn}
16
<button on:click={toggle}>
17
Log in
18
</button>
19
{/if}
Console
xxxxxxxxxx
144
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
empty,
7
init,
8
insert,
9
listen,
10
noop,
11
safe_not_equal,
12
space
13
} from "svelte/internal";
14
15
function create_if_block_1(ctx) {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */