#svelte #javascript #frontend

Day 7: Snippets & Slots

Welcome to Day 7. How do we pass HTML content into a component (like a Card wrapper)?

The Old Way: <slot>

Historically (Svelte 3/4), we used <slot>.

Card.svelte

<div class="card">
  <slot>Default Content</slot>
</div>

Parent

<Card>
  <h1>My Content</h1>
</Card>

This still works, but Svelte 5 introduces Snippets for way more power.

The New Way: Snippets (#snippet)

Snippets are reusable blocks of template logic. You can pass them around like data.

Defining a Snippet

{#snippet myIcon(color)}
  <svg fill={color}>...</svg>
{/snippet}

<!-- Using it -->
{@render myIcon('red')}
{@render myIcon('blue')}

Passing Snippets to Components

The children prop is special.

Card.svelte

<script>
  let { children } = $props();
</script>

<div class="card">
  {@render children()}
</div>

Parent

<Card>
  <p>This is implicitly the 'children' snippet!</p>
</Card>

Named Snippets (Multiple Slots)

Layout.svelte

<script>
  let { header, main, footer } = $props();
</script>

<header>{@render header()}</header>
<main>{@render main()}</main>
<footer>{@render footer()}</footer>

Parent

<script>
  import Layout from './Layout.svelte';
</script>

<Layout>
  {#snippet header()}
    <h1>My Site</h1>
  {/snippet}

  {#snippet main()}
    <p>Welcome...</p>
  {/snippet}
  
  {#snippet footer()}
    <p>Copyright 2025</p>
  {/snippet}
</Layout>

Challenge for Day 7

  1. Create a Modal.svelte.
  2. It accepts a header snippet and a body snippet (children).
  3. Render them inside a styled box.
  4. In the Parent, pass a title into the header and some paragraphs into body.

Solution:

<!-- Modal.svelte -->
<script lang="ts">
  let { header, children } = $props();
</script>

<div class="modal">
  <div class="modal-header">
    {@render header()}
  </div>
  <div class="modal-body">
    {@render children()}
  </div>
</div>

<!-- Parent -->
<Modal>
  {#snippet header()}
    <h3>Confirm Action</h3>
  {/snippet}
  
  <p>Are you sure you want to delete this?</p>
  <button>Yes</button>
</Modal>

Snippets give you full programmatic control over templates. You’ve finished Week 1! Week 2 starts with Effects and Lifecycle.