0
0
Svelteframework~5 mins

Named slots in Svelte

Choose your learning style9 modes available
Introduction

Named slots let you put different pieces of content into specific places inside a component. This helps you organize and reuse parts easily.

You want to create a card component with separate header, body, and footer areas.
You need to build a modal where the title and buttons come from outside the component.
You want to make a layout component that accepts different content for sidebar and main area.
You want to allow users to customize parts of a component without changing its structure.
Syntax
Svelte
<slot name="slotName"></slot>
Use with a name attribute inside the component to mark where content goes.
When using the component, wrap content in elements with the slot attribute matching the name, e.g.,
.
Examples
Defines three slots: a named header, a default slot, and a named footer.
Svelte
<!-- Inside component -->
<slot name="header"></slot>
<slot></slot> <!-- default slot -->
<slot name="footer"></slot>
Passes content to the named slots and default slot.
Svelte
<!-- Using component -->
<MyComponent>
  <h1 slot="header">Title here</h1>
  <p>Main content goes here.</p>
  <footer slot="footer">Footer text</footer>
</MyComponent>
Sample Program

This example shows a Card component with named slots for header and footer, plus a default slot for the body. The App component fills each slot with custom content.

Svelte
<!-- Card.svelte -->
<div class="card">
  <header class="card-header">
    <slot name="header">Default Header</slot>
  </header>
  <section class="card-body">
    <slot>Default Body Content</slot>
  </section>
  <footer class="card-footer">
    <slot name="footer">Default Footer</slot>
  </footer>
</div>

<!-- App.svelte -->
<script>
  import Card from './Card.svelte';
</script>

<Card>
  <h2 slot="header">Welcome!</h2>
  <p>This is the main card content.</p>
  <small slot="footer">Ā© 2024</small>
</Card>
OutputSuccess
Important Notes

If you don't provide content for a named slot, the default content inside the slot tag will show.

The default slot is the one without a name attribute and catches content without a slot attribute.

Named slots help keep your components flexible and easy to customize.

Summary

Named slots let you place content in specific parts of a component.

Use the slot attribute on elements when using the component to fill named slots.

They make components more reusable and organized.