Logic
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:
{#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.
App.svelte
xxxxxxxxxx
15
1
<script>
2
let user = { loggedIn: false };
3
4
function toggle() {
5
user.loggedIn = !user.loggedIn;
6
}
7
</script>
8
9
<button on:click={toggle}>
10
Log out
11
</button>
12
13
<button on:click={toggle}>
14
Log in
15
</button>
Console
xxxxxxxxxx
74
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
listen,
9
noop,
10
run_all,
11
safe_not_equal,
12
space
13
} from "svelte/internal";
14
15
function create_fragment(ctx) {
xxxxxxxxxx
74
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
listen,
9
noop,
10
run_all,
11
safe_not_equal,
12
space
13
} from "svelte/internal";
14
15
function create_fragment(ctx) {
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */
xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */