| | |

Svelte 25 ๐Ÿงก Reusable UI Templates with Snippets ({#snippet} and {@render})

โฑ๏ธ Estimated read: 7 min | |

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

SyntaxDescription
{#snippet name(args)}...{/snippet}Define a new snippet
{@render name(args)}Render a snippet
SnippetTypeScript type for snippets

Comparison

FeatureLegacy SlotSvelte 5 Snippet
Type SafetyPoorExcellent
Data PassingComplexArgument-based
LocationRigidFlexible
CompositionImplicitExplicit

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

PitfallWhy It HappensFix
Missing ImportUsing Snippet typeimport type { Snippet } from 'svelte'
Logic ErrorsImproper argument countCheck @render args
Namespace IssuesSnippet names collidingUse descriptive names
PerformanceOver-rendering snippetsBatch 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

ItemValue
Block Start{#snippet}
Rendering{@render}
TypeSnippet<[T]>
EvolutionReplaces <slot>
ReusabilityHigh

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 Snippet type 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.

Was this helpful?


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!