Svelte 25 ๐งก Reusable UI Templates with Snippets ({#snippet} and {@render})
Svelte 5 replaces the traditional <slot> mechanism with a more powerful, flexible, and type-safe feature called snippets. Snippets allow you to define chunks of template logic that can be invoked, passed as variables, or even accepted as component props. This shift transforms component composition from a structural “hole-filling” approach into a truly functional pattern where UI segments are treated as first-class, re-usable values.
Snippets provide complete control over where and how specific UI fragments are rendered. By treating markup blocks as callable functions that can accept arguments, snippets enable complex component designsโsuch as data tables with custom cell renderers or lists with item-specific templatesโto be implemented with minimal boilerplate and maximum clarity. This chapter explores how to define, pass, and render snippets within your Svelte applications.
Key point: Snippets are modular template fragments that act like functions; they allow you to define re-usable UI logic that can accept arguments, making component composition highly dynamic and fully type-safe.
Why snippets exist
The slot restriction problem. Legacy slots were restricted to specific positions within a component. If you wanted to pass a template into a complex component, you were limited by the rigid parent-child structural hierarchy.
The type-safety requirement. Unlike slots, which often involved “any” type content, snippets are defined within the Svelte reactive scope. This allows TypeScript to understand exactly what parameters a snippet expects, preventing runtime errors during template rendering.
The argument passing necessity. Slots could not easily receive dynamic data from the component that rendered them. Snippets can be invoked with arguments ({@render mySnippet(data)}), allowing for true data-driven UI composition.
The pass-as-prop flexibility. Because snippets are just template fragments, they can be passed as regular component props. This allows parent components to inject highly customized logic into children without the child needing to know the implementation details.
The clarity of functional composition. Treating UI as a series of renderable functions aligns better with modern functional programming paradigms, making your component API explicit rather than hidden behind implicit slot behavior.
a. The snippet syntax and rendering
Defining a snippet is straightforward: use the {#snippet name(args)} block. You then use {@render name(args)} to invoke it. Snippets can be defined locally within a component or exported to be shared across multiple components, which creates a shared library of UI fragments.
{#snippet mySnippet(text)}
<p>Hello, {text}!</p>
{/snippet}
{@render mySnippet("World")}
The rendering mechanism is essentially a function call. Because Svelte compiles these blocks into efficient functions, they perform significantly better than legacy slots. You can define as many snippets as you need in a single component, and you can render them in any order, multiple times, or even conditionally based on your reactive logic.
b. Passing snippets as component props
The true power of snippets lies in their ability to be passed as props. By typing a prop as a Snippet (imported from svelte), you allow the parent to define the look and feel of the child component’s internal parts. This is ideal for components like tables or cards that need to render unknown data structures.
import type { Snippet } from 'svelte';
let { title, children }: { title: string, children: Snippet } = $props();
In the child component, you simply call {@render children()}. This approach is much cleaner than the legacy <slot /> or named <slot name="header" /> syntax, as it uses standard JavaScript prop passing rather than a specialized HTML-like slot architecture.
c. Snippets with arguments
Snippets can accept arguments, turning them into dynamic templates. This is particularly useful for loops or lists where you want to provide a “template function” that the list component calls for every item. The parent defines the visual representation, and the child manages the iteration logic.
{#snippet row(item)}
<tr><td>{item.id}</td><td>{item.val}</td></tr>
{/snippet}
<Table {items} itemRenderer={row} />
Inside the child component, you invoke itemRenderer with the current item as an argument. This pattern decouples the list management from the item rendering logic. It provides the flexibility of a high-order function while maintaining the readability and declarative nature of the Svelte template syntax.
Complete Example Session
// ============================================
// PART 1: DEFINING A SNIPPET
// ============================================
{#snippet card(title, content)}
<div class="card">
<h3>{title}</h3>
<div>{@render content()}</div>
</div>
{/snippet}
// ============================================
// PART 2: PASSING A SNIPPET AS PROP
// ============================================
// Component.svelte
let { header }: { header: Snippet } = $props();
<header>{@render header()}</header>
// ============================================
// PART 3: INVOKING THE SNIPPET
// ============================================
// App.svelte
{#snippet myHeader()}
<h1>Logo</h1>
{/snippet}
<Component header={myHeader} />
This sequence demonstrates how to create a template fragment, pass it as a component property, and render it inside the component scope.
Quick Reference
Snippet Syntax
| Syntax | Description |
|---|---|
{#snippet name(args)}...{/snippet} | Define a new snippet |
{@render name(args)} | Render a snippet |
Snippet | TypeScript type for snippets |
Comparison
| Feature | Legacy Slot | Svelte 5 Snippet |
|---|---|---|
| Type Safety | Poor | Excellent |
| Data Passing | Complex | Argument-based |
| Location | Rigid | Flexible |
| Composition | Implicit | Explicit |
Best Practices
โ Do This:
// Type your snippets for clarity
let { row }: { row: Snippet<[Item]> } = $props(); // โ
// Define reusable snippets in a separate file
export const mySnippet = ...; // โ
// Use for flexible table cell rendering
{@render cell(item)} // โ
โ Don’t Do This:
// Don't use legacy <slot> in new Svelte 5 apps
<slot /> // โ
// Don't pass large, complex snippets without args
// (causes re-render overhead) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Missing Import | Using Snippet type | import type { Snippet } from 'svelte' |
| Logic Errors | Improper argument count | Check @render args |
| Namespace Issues | Snippet names colliding | Use descriptive names |
| Performance | Over-rendering snippets | Batch reactivity |
Real-World Examples
1. Custom Table Cell
{#snippet cell(val)}<td>{val}</td>{/each}
2. Modal Header
{#snippet modalHeader(title)}<h2>{title}</h2>{/snippet}
3. List Item Decorator
{#snippet item(text)}<li>- {text}</li>{/snippet}
4. Card Footer
{#snippet footer(actions)}<footer>{@render actions()}</footer>{/snippet}
5. Form Error Helper
{#snippet error(msg)}<span class="err">{msg}</span>{/snippet}
6. Tooltip Content
{#snippet tooltip(content)}<div class="tip">{content}</div>{/snippet}
7. Icon Renderer
{#snippet icon(name)}<svg class={name} />{/snippet}
8. Data Grid Renderer
{#snippet row(data)}<tr>{@render data()}</tr>{/snippet}
9. Nav Link
{#snippet link(path, label)}<a href={path}>{label}</a>{/snippet}
10. Empty State Template
{#snippet empty()}<div>No data found</div>{/snippet}
Visual
Slot vs. Snippet Composition
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SLOTS (Rigid) โ
โ [ Child Component Slot ] โ
โ โโโ Content limited to parent โ
โ โ
โ SNIPPETS (Flexible) โ
โ [ Child Component Snippet Props ] โ
โ โโโ Snippet can be shared, โ
โ passed around, and reused โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Rendering Workflow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SNIPPET DEFINITION (Template Logic) โ
โ โ โ
โ {@render name()} โโโบ (Invocation) โ
โ โ โ
โ DOM INJECTION (Where needed) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Block Start | {#snippet} |
| Rendering | {@render} |
| Type | Snippet<[T]> |
| Evolution | Replaces <slot> |
| Reusability | High |
Key takeaways:
- Snippets are functional templates. Treat them as functions that return UI nodes, accepting arguments to remain dynamic.
- Replace slots. Move away from
<slot />and embrace$props()-based snippet injection for all new Svelte 5 components. - Type safety is key. Use the
Snippettype from Svelte to ensure your component contracts are fully enforced by TypeScript. - Composition over structure. Snippets allow you to pass complex UI patterns as props, enabling much flatter and more reusable component trees.
- Shared libraries. Define common UI snippets in shared files to create a consistent design language across your entire application.
Remember: Snippets represent the maturation of Svelteโs component model. By moving from structural slots to functional snippets, Svelte allows you to express your UI composition with the same clarity and type-safety as your JavaScript business logic. Use snippets to break down complex components into smaller, re-usable fragments, and you will find your application architecture becomes significantly more modular and easier to evolve.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!