No More Copy-Paste Hell! Intro to Astro Dynamic Routing♪
Netsuki
No More Copy-Paste Hell! Intro to Astro Dynamic Routing♪
#Web
Quick Recap: Static Routing
src/pages/
├── index.astro → /
├── about.astro → /about
└── blog/
└── index.astro → /blog
Dynamic Routing Basics
/blog/first-post
/blog/second-post
/blog/third-post
...
src/pages/blog/
├── first-post.astro
├── second-post.astro
├── third-post.astro
...(100 more files)
src/pages/blog/
└── [slug].astro → /blog/first-post, /blog/second-post, etc.
Defining Routes with getStaticPaths
---
// src/pages/blog/[slug].astro
export function getStaticPaths() {
return [
{ params: { slug: 'first-post' } },
{ params: { slug: 'second-post' } },
{ params: { slug: 'third-post' } },
];
}
const { slug } = Astro.params;
---
<h1>Post: {slug}</h1>
dist/
└── blog/
├── first-post/index.html
├── second-post/index.html
└── third-post/index.html
Passing Data with Props
---
// src/pages/blog/[slug].astro
export function getStaticPaths() {
const posts = [
{ slug: 'first-post', title: 'First Post', content: 'Hello!' },
{ slug: 'second-post', title: 'Second Post', content: 'See ya!' },
];
return posts.map((post) => ({
params: { slug: post.slug },
props: { title: post.title, content: post.content },
}));
}
const { slug } = Astro.params;
const { title, content } = Astro.props;
---
<article>
<h1>{title}</h1>
<p>{content}</p>
</article>
Multiple Levels? Rest Parameters!
---
// src/pages/docs/[...slug].astro
export function getStaticPaths() {
return [
{ params: { slug: undefined } }, // → /docs
{ params: { slug: 'getting-started' } }, // → /docs/getting-started
{ params: { slug: 'guides/routing' } }, // → /docs/guides/routing
{ params: { slug: 'guides/styling' } }, // → /docs/guides/styling
];
}
const { slug } = Astro.params;
---
<h1>Docs: {slug || 'Top'}</h1>
/[org]/[repo]/tree/[branch]/[...file]
↓
/withastro/astro/tree/main/docs/public/favicon.svg
Real Example: This Site’s i18n
src/pages/
└── [...lang]/
├── index.astro → /, /en
├── profile.astro → /profile, /en/profile
├── diary/
│ └── [...slug].astro → /diary/2025-12-09, /en/diary/2025-12-09
...
---
// src/pages/[...lang]/index.astro
export function getStaticPaths() {
return [
{ params: { lang: undefined }, props: { lang: 'ja' } }, // → /
{ params: { lang: 'en' }, props: { lang: 'en' } }, // → /en
];
}
const { lang } = Astro.props;
---
<h1>{lang === 'ja' ? 'ようこそ!' : 'Welcome!'}</h1>
Netsuki’s Wrap-up
♪ Web Clap ♪
0 claps