コピペ地獄からの解放!Astroの動的ルーティング入門♪
ねつき
コピペ地獄からの解放!Astroの動的ルーティング入門♪
#Web
静的ルーティングのおさらい
src/pages/
├── index.astro → /
├── about.astro → /about
└── blog/
└── index.astro → /blog
動的ルーティングの基本
/blog/first-post
/blog/second-post
/blog/third-post
...
src/pages/blog/
├── first-post.astro
├── second-post.astro
├── third-post.astro
...(100個続く)
src/pages/blog/
└── [slug].astro → /blog/first-post, /blog/second-post, etc.
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>記事: {slug}</h1>
dist/
└── blog/
├── first-post/index.html
├── second-post/index.html
└── third-post/index.html
propsでデータを渡す
---
// src/pages/blog/[slug].astro
export function getStaticPaths() {
const posts = [
{ slug: 'first-post', title: '最初の記事', content: 'こんにちは!' },
{ slug: 'second-post', title: '2番目の記事', content: 'またね!' },
];
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>
複数階層もOK!レストパラメータ
---
// 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>ドキュメント: {slug || 'トップ'}</h1>
/[org]/[repo]/tree/[branch]/[...file]
↓
/withastro/astro/tree/main/docs/public/favicon.svg
実際の使用例:このサイトの多言語対応
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>
ねつき的まとめ
♪ 拍手 ♪
0 拍手