Layouts & slots · Lesson 8 of 22 · 15 min
Named slots and the Section component
Build a Section component with more than one slot, then lay out the homepage.
A component can have more than one slot. Give extra slots a name, and the parent decides what goes in each one.
Your homepage will have several sections that share the same shape: a title, an optional intro line, and a body. That’s a job for one Section component.
1. Create Section.astro
src/components/Section.astro
---
interface Props {
id?: string;
title: string;
}
const { id, title } = Astro.props;
---
<section id={id}>
<div class="container">
<h2>{title}</h2>
<slot name="intro" />
<div class="body">
<slot />
</div>
</div>
</section>
<style>
section {
padding: 3rem 0;
}
h2 {
font-size: 1.75rem;
margin: 0 0 0.5rem;
}
.body {
margin-top: 1.5rem;
}
</style>
It has two slots:
<slot name="intro" />for a short line under the heading<slot />(the default slot) for everything else
2. Fill the slots
To send content to a named slot, add slot="name" to the element. Anything without a slot attribute goes to the default slot.
src/pages/index.astro
---
import BaseLayout from '../layouts/BaseLayout.astro';
import Section from '../components/Section.astro';
---
<BaseLayout title="Home">
<section class="hero">
<div class="container">
<h1>Seasonal home cooking for your table.</h1>
<p>Private dinners, weekly meal prep, and cooking classes in Sonora, CA.</p>
<a class="button" href="#services">See what we offer</a>
</div>
</section>
<Section id="services" title="Services">
<p slot="intro">Pick the one that fits your week.</p>
<p>Service cards go here in the next lesson.</p>
</Section>
</BaseLayout>
<style>
.hero {
padding: 5rem 0 3rem;
}
.hero h1 {
font-size: clamp(2rem, 5vw, 3.25rem);
line-height: 1.1;
margin: 0 0 1rem;
max-width: 18ch;
}
.hero p {
font-size: 1.2rem;
color: var(--color-muted);
}
.button {
display: inline-block;
margin-top: 1rem;
padding: 0.75rem 1.25rem;
border-radius: var(--radius);
background: var(--color-accent);
color: white;
text-decoration: none;
font-weight: 600;
}
</style>
The order you write things in the parent doesn’t matter. The intro paragraph lands under the heading because that’s where the Section put its named slot.
The See what we offer button links to #services, which jumps to the section with id="services". That’s why Section takes an id prop.
Check if a slot was filled
Sometimes you want to skip a wrapper when a slot is empty. Astro.slots.has() tells you:
{Astro.slots.has('intro') && (
<div class="intro">
<slot name="intro" />
</div>
)}