Svelte and SvelteKit 5 cheatsheet
Svelte and SvelteKit 5: Template syntax
9 common Svelte and SvelteKit 5 tasks.
Show content conditionally
Use {#if} blocks, with {:else if} and {:else} branches.
{#if user}
<p>Welcome, {user.name}</p>
{:else}
<p>Please sign in</p>
{/if}
Loop over a list
Give each item a key, in parentheses, so Svelte can update the list efficiently.
<ul>
{#each items as item (item.id)}
<li>{item.name}</li>
{:else}
<li>Nothing here</li>
{/each}
</ul>
Show an async result
Render pending, success and error states of a promise.
{#await promise}
<p>Loading...</p>
{:then data}
<p>{data.title}</p>
{:catch error}
<p>Failed: {error.message}</p>
{/await}
Bind form inputs
bind:value keeps a variable and an input in sync in both directions.
<input bind:value={name} />
<input type="checkbox" bind:checked={subscribed} />
<select bind:value={size}>...</select>
Handle events
Events are properties like onclick. Call preventDefault yourself when needed.
<button onclick={save}>Save</button>
<form onsubmit={(e) => { e.preventDefault(); submit(); }}>...</form>
Toggle classes
Add a class conditionally with an object or array in the class attribute.
<div class={["card", { active: isActive, disabled }]}>...</div>
Reusable markup with snippets
Define a snippet once and render it where you need it, with parameters.
{#snippet row(item)}
<li>{item.name} - {item.price}</li>
{/snippet}
<ul>
{#each products as product}
{@render row(product)}
{/each}
</ul>
Accept child content
Render the content passed between a component's tags.
<script lang="ts">
let { children } = $props();
</script>
<div class="panel">
{@render children?.()}
</div>
Animate elements entering and leaving
Apply a built-in transition to elements added or removed by blocks.
<script>
import { fade } from "svelte/transition";
</script>
{#if visible}
<p transition:fade>Hello</p>
{/if}