Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Layouts and slots

A layout is a component with the markup shared by all pages: <html>, <head>, the header and the footer. A page passes only its own content into the layout. The place where it goes is marked with the <slot /> tag, a slot.

A layout

Create the folder src/layouts and the file src/layouts/BaseLayout.astro:

---
import Header from '../components/Header.astro';
 
interface Props {
  title: string;
}
 
const { title } = Astro.props;
---
 
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{title} | Anna's blog</title>
  </head>
  <body>
    <Header />
    <main>
      <slot />
    </main>
    <footer>Anna's blog, 2025</footer>
  </body>
</html>

This is an ordinary component with a title prop. The <slot /> tag is where Astro inserts everything the page writes between the opening and closing tags of the layout.

A page inside the layout

Rewrite src/pages/about.astro:

---
import BaseLayout from '../layouts/BaseLayout.astro';
---
 
<BaseLayout title="About me">
  <h1>About me</h1>
  <p>My name is Anna, I write about web development.</p>
</BaseLayout>

Open /about: the page now has the header, the footer and the tab title "About me | Anna's blog". The heading and paragraph took the place of <slot />. Wrap index.astro and posts/index.astro the same way, and you no longer repeat <head> in every page.

Named slots

Sometimes content has to go into several places. A slot gets a name, and the page marks an element with the slot attribute. Add a sidebar to the layout:

<main>
  <slot />
</main>
<aside>
  <slot name="sidebar">
    <p>Subscribe to the RSS feed.</p>
  </slot>
</aside>

The text inside <slot name="sidebar"> is fallback content: it is shown when the page passes nothing. A page fills the slot like this:

<BaseLayout title="Posts">
  <h1>Posts</h1>
  <nav slot="sidebar">
    <a href="/tags/astro">astro</a>
  </nav>
</BaseLayout>

The post list goes into <main>, and the tag navigation into <aside>.

Nested layouts

A layout can use another layout. For example, src/layouts/PostLayout.astro wraps a post in BaseLayout and adds the date and author. Posts get their own design while the header and footer stay shared.

Common mistake

People forget to write <slot /> in the layout. The page opens with the header and footer, but its own content disappears without any error. If a page suddenly looks "empty", check the slot in the layout first.

Thanks for reading!

Donate to the site — we work hard for you.