Svelte 5 Template Syntax
Svelte 5 template blocks ({#if}, {#each}, {#key}, {#await}, {#snippet}) and tags ({@render}, {@html}, {@attach}, {@const}, {@debug}) for declarative UI logic.
Svelte 5 uses a template syntax that blends HTML with declarative control-flow blocks and special tags. These constructs allow conditional rendering, iteration, asynchronous handling, and reusable template fragments.
Control Flow Blocks
{#if}
Conditionally renders content based on a JavaScript expression.
{#if condition}
<p>Condition is truthy</p>
{:else if other}
<p>Other is truthy</p>
{:else}
<p>Neither is truthy</p>
{/if} {#each}
Iterates over arrays and iterables.
{#each items as item, index (key)}
<p>{index}: {item.name}</p>
{/each} The (key) expression provides a stable identity for each item, enabling efficient DOM updates on reorder. Use {:else} for the empty-state fallback.
{#key}
Forces a DOM element or component to be destroyed and recreated when the key expression changes.
{#key value}
<ExpensiveComponent data={value} />
{/key} {#await}
Handles promise states declaratively — pending, resolved, and rejected.
{#await promise}
<p>Loading...</p>
{:then value}
<p>Resolved: {value}</p>
{:catch error}
<p>Error: {error.message}</p>
{/await} For promises in load functions, SvelteKit also supports streaming data with top-level await expressions in components.
{#snippet} and {@render}
Snippets are reusable template fragments that can be passed as props. They replace slots from Svelte 4.
{#snippet mySnippet(data)}
<p>Rendered: {data}</p>
{/snippet}
{@render mySnippet("hello")} Snippets can be passed to child components as props, enabling flexible composition patterns. Children render snippets with {@render children?.()} or {@render namedSnippet(data)}.
Template Tags
{@html}
Renders a string as raw HTML. Caution: does not sanitize — ensure the content is trusted.
{@html contentString} {@debug}
Opens a debugger breakpoint when the surrounding state changes. Only active in development mode.
{@debug variable} {@const}
Defines a local constant within a block scope.
{#each items as item}
{@const total = item.price * item.quantity}
<p>{total}</p>
{/each} Await Expressions
Svelte 5 introduces {% await expression %} — top-level await expressions that work in .svelte components for simpler async data access.
See Also
- Svelte 5 Template Directives — bind:, class:, style:, use:, transition:, animate:
- Svelte 5 Runes — the reactive primitives behind template logic
- Svelte Built-in Components — special elements with framework integration
