Routes & ship · Lesson 13 of 22 · 15 min
One page per post with dynamic routes
Use a [bracket] file and getStaticPaths to generate a page for every post.
You have three posts and you’ll write more. You don’t want a file per post in src/pages/. Instead you write one file that works as a template, and Astro builds a page for each post.
Brackets make a route dynamic
A file named [id].astro matches any single segment of a URL. Inside src/pages/blog/, it matches /blog/fall-menu, /blog/first-supper, and so on. The part in brackets becomes a parameter called id.
1. Create the post page
src/pages/blog/[id].astro
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getCollection, render } from 'astro:content';
export async function getStaticPaths() {
const posts = await getCollection('blog', ({ data }) => !data.draft);
return posts.map((post) => ({
params: { id: post.id },
props: { post },
}));
}
const { post } = Astro.props;
const { Content } = await render(post);
const { title, description, pubDate, tags } = post.data;
---
<BaseLayout title={title} description={description}>
<article class="container post">
<p><a href="/blog">← All posts</a></p>
<h1>{title}</h1>
<time datetime={pubDate.toISOString()}>
{pubDate.toLocaleDateString('en-US', { dateStyle: 'long', timeZone: 'UTC' })}
</time>
{tags.length > 0 && (
<ul class="tags">
{tags.map((tag) => <li>{tag}</li>)}
</ul>
)}
<Content />
</article>
</BaseLayout>
<style>
.post {
max-width: 680px;
padding-top: 2rem;
}
time {
color: var(--color-muted);
}
.tags {
display: flex;
gap: 0.5rem;
list-style: none;
padding: 0;
}
.tags li {
background: #f3e8dc;
padding: 0.15rem 0.6rem;
border-radius: 999px;
font-size: 0.85rem;
}
</style>
How it works, step by step
- At build time, Astro sees the brackets and calls
getStaticPaths(). - That function returns a list. Each item has
params(what goes in the URL) andprops(data to hand the page). - Astro builds the page once per item. For
{ params: { id: 'fall-menu' } }it writes/blog/fall-menu/index.html. - Each time,
Astro.props.postis that item’s post. render(post)turns the Markdown body into a<Content />component you drop anywhere.
The id in params must match the name in the brackets. [id].astro needs params: { id }.
Try the links
Go to /blog and click any post. You get the title, date, tags, and the full Markdown body, all inside your layout. Add a new .md file to src/content/blog/ and a new page appears. No new code.