🤔 Imagine you're building a website with:
- Same Header ✅
- Same Navigation ✅
- Same Footer ✅
- Different page content ✅
Instead of copying the Header and Footer into every page, Astro lets you create a Layout.
Think of a Layout as a reusable page frame.
+------------------+
| Header / Navbar |
+------------------+
| |
| Page Content |
| (<slot />) |
| |
+------------------+
| Footer |
+------------------+
⚙️ How It Works
Step 1: Create a Layout
---
import Navbar from '../components/Navbar.astro';
import Footer from '../components/Footer.astro';
const { title } = Astro.props;
---
<html>
<head>
<Navbar title={title} />
</head>
<body>
<h1>{title}</h1>
<article>
<slot />
</article>
<Footer />
</body>
</html>
The magic is:
<slot />
Everything placed between the layout tags will be injected into that slot.
Step 2: Use the Layout
---
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Home Page">
<p>Hello from Home Page!</p>
</BaseLayout>
Astro automatically inserts the content inside the Layout's:
<slot />
🎯 Why Use Layouts?
Without Layouts
Page 1
├─ Header
├─ Footer
Page 2
├─ Header
├─ Footer
Page 3
├─ Header
├─ Footer
Lots of duplicated code 😫
With Layouts
BaseLayout
├─ Header
├─ Slot
└─ Footer
Page 1 → Content A
Page 2 → Content B
Page 3 → Content C
Cleaner, reusable, and easier to maintain ✅
📝 Layouts with Markdown
Astro can also apply Layouts to:
.md.mdx
Example:
---
layout: ../layouts/BaseLayout.astro
title: "My Article"
author: "Asmaa"
---
Your Markdown content is automatically injected into:
<slot />
This makes blogs and documentation sites very easy to build.
📖 Accessing Frontmatter
Markdown metadata (frontmatter) can be read inside the layout.
Markdown File
---
layout: ../layouts/BaseLayout.astro
title: "My First Astro Article"
author: "Asmaa"
date: "29 Oct 2026"
---
Layout File
---
const { frontmatter } = Astro.props;
---
<h1>{frontmatter.title}</h1>
<slot />
<p>Written by {frontmatter.author}</p>
<p>Date: {frontmatter.date}</p>
🧩 MDX Layouts
For MDX files, you can manually import a Layout and pass custom props.
---
import BaseLayout from '../../layouts/BaseLayout.astro';
function fancyJsHelper() {
return "Welcome to Astro!";
}
---
<BaseLayout
title={frontmatter.title}
fancyJsHelper={fancyJsHelper}
>
My MDX Content
</BaseLayout>
Inside the Layout:
---
const { title, fancyJsHelper } = Astro.props;
---
<h1>{title}</h1>
<slot />
<p>{fancyJsHelper()}</p>
This allows MDX pages to use JavaScript and custom logic.
⭐ Key Takeaway
Astro Layouts = Reusable Page Templates
They help you:
- Reuse Header/Footer
- Keep a consistent design
- Reduce duplicated code
- Build blogs and documentation easily
- Inject page content using
<slot /> - Share common UI across the entire site
Simple Analogy
Think of a Layout as a house blueprint 🏠
- Walls, doors, and roof = Layout
- Furniture inside each room = Page Content
You build the structure once and reuse it everywhere.
Top comments (0)