Components and layouts

Compose and check a nested Astro post layout

Build a post layout around your shared page shell, pass metadata through both components, and test missing props and slots.

We will add a post layout to the shared page shell, then check the generated HTML. This exercise focuses on nesting layouts and catching missing metadata or content.

Start with src/layouts/Layout.astro from the Astro layouts tutorial. It accepts required title and description props and has a <slot /> inside <main>.

Add the post wrapper

Save this as src/layouts/PostLayout.astro:

---
import Layout from './Layout.astro'

interface Props {
  title: string
  description: string
  date: Date
}

const { title, description, date } = Astro.props
---

<Layout title={title} description={description}>
  <article>
    <h1>{title}</h1>
    <time>{date.toLocaleDateString('en-GB')}</time>
    <slot />
  </article>
</Layout>

Pages pick the most specific layout they need. Nested layouts still cost nothing in the browser, because they all render on the server.

The post wrapper passes metadata to the outer layout. Its slot places the page content below the post heading and date.

Save a test page as src/pages/layout-check.astro:

---
import PostLayout from '../layouts/PostLayout.astro'
---

<PostLayout
  title="My first post"
  description="A test of our nested layouts"
  date={new Date('2026-01-01T12:00:00Z')}>
  <p>This sentence should appear inside the article.</p>
</PostLayout>

Check the rendered document

Run the development server and open /layout-check/. Confirm the navigation, post title, date, sentence and footer all appear.

Build the site and inspect dist/layout-check/index.html. There should be one document shell, with the title and description in its head. The article belongs inside the base layout’s <main>; the nested layout should not add another <html> or <body>.

Add another page using PostLayout with different metadata and content. Change the base footer once, then check both routes. Both should show the new footer while keeping their own titles.

Try the failures

Remove description from the test page. The editor should flag the missing required prop. Run npx astro check with Astro’s check tooling installed to confirm it. astro build renders the site but does not perform this type check.

Restore the prop, then temporarily remove <slot /> from PostLayout. The shell still renders, but the test sentence disappears. Restore the slot and repeat the test with the base layout’s slot: now the whole article disappears.

Restore both slots before finishing. The completed exercise has two routes sharing one shell, correct metadata on each route, and their content visible through both layout layers.

Lesson completed