Svelte logo

Svelte by Example: Snippets

Snippets are reusable pieces of markup. They can be rendered in a component, or passed to another component as props.

In this example, we'll wrap our todo list in a layout component.

Content passed inside a component becomes a snippet prop called children. Named snippets can be passed as props too.

Use {@render} to render a snippet. The parentheses are required, even when there are no parameters.

Check whether an optional snippet was provided before rendering it.

Layout.svelte
<script>
  let { children, footer } = $props();
</script>


<main>
  {@render children()}
</main>


{#if footer}
  <footer>
    {@render footer()}
  </footer>
{/if}

Our heading and list become the layout's children snippet.

A named snippet declared inside a component is passed to that component as a prop.

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

<Layout>
  <h1>Todo List</h1>
  <ul>
    <li>Walk dog</li>
  </ul>


  {#snippet footer()}
    <p>One todo at a time.</p>
  {/snippet}
</Layout>

Snippet Parameters

Snippets can receive parameters. Here, we'll reuse the same markup for each todo.

Pass a value when rendering the snippet.

TodoList.svelte
<script>
  let todos = $state(['Walk dog', 'Read newspaper']);
</script>


{#snippet item(task)}
  <li>{task}</li>
{/snippet}

<ul>
  {#each todos as task}
    {@render item(task)}
  {/each}
</ul>