Snippets & Render
Snippets: reusable chunks of markup
Section titled “Snippets: reusable chunks of markup”A snippet is a named block of markup you can render multiple times. Define it with {#snippet name(params)}…{/snippet} and render it with {@render name(args)}. It’s Svelte’s way to stay DRY inside a template.
<script> let items = $state([ { name: 'Coffee', price: 3 }, { name: 'Tea', price: 2 }, ]);</script>
{#snippet row(item)} <tr><td>{item.name}</td><td>${item.price}</td></tr>{/snippet}
<table> {#each items as item (item.name)} {@render row(item)} {/each}</table>The snippet row is defined once and rendered per item. Snippets take parameters like functions, so the same markup adapts to different data.
flowchart LR
def["{#snippet row(item)} ... {/snippet}"] --> render1["{@render row(a)}"]
def --> render2["{@render row(b)}"]
render1 --> out["markup instances"]
render2 --> out Snippets replaced slots
Section titled “Snippets replaced slots”In Svelte 4, you passed markup into a component with <slot> (and named slots via <slot name="x">). Svelte 5 replaced that entirely with snippets — they’re more powerful because they can take parameters and are just values you pass around.
<!-- Svelte 4 (old): a component defined <slot /> and <slot name="header" /> --><!-- Svelte 5 (new): a component renders {@render children()} and {@render header()} -->If you’re reading older tutorials that use <slot>, the modern equivalent is a snippet rendered with {@render}. The next lesson covers exactly how a parent passes snippets (including the special children snippet) into a child.
Snippets are values
Section titled “Snippets are values”Because a snippet is a value, you can pass it to another snippet, store it in a variable, or choose between snippets conditionally:
{#snippet loading()}<p>Loading…</p>{/snippet}{#snippet ready(data)}<p>{data}</p>{/snippet}
{#if isLoading} {@render loading()}{:else} {@render ready(result)}{/if}This composability — snippets as first-class, parameterized values — is why they replaced the more rigid slot mechanism.