Share a layout across pages
Stop repeating yourself. Build a layout and a navigation menu that every page can use.
Tested on Astro 7.4
A component is a reusable piece of a page. A layout is a component that wraps a whole page. You’ll make one of each.
Create a navigation component
Create src/components/Nav.astro. You’ll need to make the components folder first.
<nav>
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
</nav>
<style>
nav {
display: flex;
gap: 1rem;
padding-block: 1rem;
}
</style>
Styles written inside a component apply only to that component. So this nav rule can’t affect any other part of your site.
Create a layout
Create src/layouts/Layout.astro:
---
import Nav from '../components/Nav.astro';
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
</head>
<body>
<Nav />
<main>
<slot />
</main>
</body>
</html>
Two lines do the clever work. Astro.props receives the page title, and <slot /> marks where each page’s content goes.
Use the layout
Replace src/pages/index.astro with this:
---
import Layout from '../layouts/Layout.astro';
const name = 'Sam';
---
<Layout title="Home">
<h1>Hello, I'm {name}</h1>
<p>This is my first website.</p>
</Layout>
And replace src/pages/about.astro with this:
---
import Layout from '../layouts/Layout.astro';
---
<Layout title="About">
<h1>About me</h1>
<p>I'm learning to build websites with Astro.</p>
</Layout>
Both pages now have the menu. Change the menu once, and it changes everywhere.
What you’ve done
Your site has a shared design. The Blog link goes nowhere yet, so let’s build the blog.
Star lit. See your progress