Skip to main content
Snippets are Svelte 5’s way to create reusable chunks of markup and pass content between components. They replace the legacy <slot> syntax with a more powerful and flexible system.

Snippets: The Basics

Snippets let you define reusable markup chunks:
1
Declaring Snippets
2
Snippets can have parameters with default values:
3
{#snippet greeting(name = 'world')}
  <p>Hello {name}!</p>
{/snippet}

{@render greeting()}
{@render greeting('Alice')}
4
Rendering Snippets
5
Use the @render tag to render snippets:
6
{#snippet card(title, description)}
  <div class="card">
    <h2>{title}</h2>
    <p>{description}</p>
  </div>
{/snippet}

{@render card('Welcome', 'This is a card component')}
7
Snippet Scope
8
Snippets can reference values from outer scopes:
9
<script>
  let { message = "it's great to see you!" } = $props();
</script>

{#snippet hello(name)}
  <p>hello {name}! {message}!</p>
{/snippet}

{@render hello('alice')}
{@render hello('bob')}

Passing Snippets to Components

Explicit Snippet Props

Pass snippets as props to create flexible, composable components:

Implicit Snippet Props

Snippets declared inside component tags automatically become props:

The Children Snippet

Content that’s not in a named snippet becomes the children snippet:
This is the equivalent of Svelte 4’s default slot.

Optional Snippets

Make snippets optional with optional chaining or conditional rendering:

Typing Snippets

Use the Snippet interface from svelte for type safety:
The type argument is a tuple representing snippet parameters:

Generic Snippet Types

Create type-safe snippets with generics:

Snippet Patterns

Render Props Pattern

Pass data from parent to snippet parameters:

Recursive Snippets

Snippets can reference themselves:

Conditional Rendering

Provide different snippet implementations:

Exporting Snippets

Snippets can be exported from <script module>:

Programmatic Snippets

Create snippets programmatically with createRawSnippet:

Legacy Slots (Svelte 4)

In Svelte 4, content was passed using <slot> elements. This is now deprecated:

Best Practices

  1. Name snippets clearly - Use descriptive names that indicate what the snippet renders
  2. Document parameters - Make it clear what data snippets expect
  3. Provide fallbacks - Use optional chaining or conditional rendering for optional snippets
  4. Type your snippets - Use TypeScript for better autocomplete and error checking
  5. Keep snippets focused - Each snippet should have a single, clear purpose