Layouts & slots · Lesson 7 of 22 · 15 min
Layouts and the slot element
Wrap every page in one shared shell using a layout component and a slot.
Right now the <html>, <head>, and <Header> live inside index.astro. Every new page would have to copy them. A layout fixes that: one component holds the shell, and each page fills in the middle.
The tool that makes this work is <slot />. It’s a placeholder that says “put whatever the parent passed in here.”
1. Add a Footer
src/components/Footer.astro
---
const year = new Date().getFullYear();
---
<footer>
<div class="container">
<p>© {year} Sunday Supper Co. Built with Astro.</p>
</div>
</footer>
<style>
footer {
margin-top: 4rem;
padding: 2rem 0;
color: var(--color-muted);
border-top: 1px solid #eadfd2;
}
</style>
2. Create the layout
Make a src/layouts/ folder and add BaseLayout.astro:
src/layouts/BaseLayout.astro
---
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
import '../styles/global.css';
interface Props {
title: string;
description?: string;
}
const { title, description = 'Seasonal home cooking for your table.' } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content={description} />
<title>{title} | Sunday Supper Co.</title>
</head>
<body>
<Header siteName="Sunday Supper Co." />
<main>
<slot />
</main>
<Footer />
</body>
</html>
Notice the global CSS import moved here. Every page that uses the layout gets it.
3. Use the layout on the homepage
Replace index.astro:
src/pages/index.astro
---
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Home">
<div class="container">
<h1>Seasonal home cooking for your table.</h1>
<p>Private dinners, weekly meal prep, and cooking classes in Sonora, CA.</p>
</div>
</BaseLayout>
Everything between <BaseLayout> and </BaseLayout> gets dropped where <slot /> is. The page went from 25 lines to 10, and the next page you make will be just as short.
Fallback content
A slot can have default content that shows when the parent passes nothing:
<slot>
<p>Nothing here yet.</p>
</slot>
Layouts are just components
There’s nothing magic about the layouts/ folder. A layout is a regular component that happens to include <html> and a slot. You can nest them too: a BlogLayout could use BaseLayout inside it.