javascript / expert
Snippet
Reusable UI Logic with Svelte 5 Snippets
Snippets allow you to define reusable chunks of markup within a component. They replace the older slot mechanism with a more flexible, function-like approach that can accept arguments and be rendered dynamically.
snippet.js
1
2
3
4
5
6
7
8
9
10
{#snippet userCard(user)}<div class="card"><h3>{user.name}</h3>{@render children?.()}</div>{/snippet}{@render userCard({ name: 'Expert' })}<p>Extra content via children.</p>{/render}
svelte
Breakdown
1
{#snippet userCard(user)}
Defines a snippet named 'userCard' that takes 'user' as a parameter.
2
{@render children?.()}
Renders the nested content passed to the snippet, similar to slots.
3
{@render userCard(...)}
Invokes the snippet with specific data.