Snippets are a way to create reusable chunks of markup inside your components. They’re more powerful and flexible than Svelte 4’s slots.
Basic Syntax
With parameters:
Creating Snippets
Define reusable markup to avoid duplication:
Rendering Snippets
Use {@render} to render a snippet:
Snippet Parameters
Snippets can have parameters with default values and destructuring:
Snippets cannot use rest parameters (...rest). Each parameter must be explicitly named.
Snippet Scope
Snippets can reference values from their surrounding context:
Snippets are visible to siblings and children:
Recursive Snippets
Snippets can reference themselves:
Passing Snippets to Components
As Explicit Props
Pass snippets like any other prop:
As Implicit Props
Snippets declared inside component tags become props automatically:
The Children Snippet
Content that isn’t a snippet declaration becomes the children snippet:
Don’t have a prop named children if your component also has content inside its tags.
Optional Snippets
Make snippets optional with optional chaining or if blocks:
TypeScript Support
Type snippets using the Snippet interface:
With generics for type safety:
Real-World Use Cases
Exporting Snippets
Export snippets from <script module> for use in other components:
Snippet exports require Svelte 5.5.0 or newer. Exported snippets cannot reference non-module <script> declarations.
Migration from Slots
Snippets replace Svelte 4 slots: