Astro 的路由是文件系统路由。
src/pages/index.astro -> /
src/pages/about.astro -> /about
src/pages/exhibitions/index.astro -> /exhibitions
src/pages/exhibitions/[slug].astro -> /exhibitions/:slug
src/pages/docs/[...slug].astro -> /docs/*你可以把它理解为:
- 每个文件,就是一个展馆或一段栈桥
- 文件名,就是泊位编号
- 目录结构,就是群岛地图
动态路由例子:
---
// src/pages/exhibitions/[slug].astro
import { getCollection, render } from 'astro:content';
export async function getStaticPaths() {
const exhibitions = await getCollection('exhibitions');
return exhibitions.map((entry) => ({
params: { slug: entry.id },
props: { entry },
}));
}
const { entry } = Astro.props;
const { Content, headings } = await render(entry);
---
<html lang="zh-CN">
<head>
<title>{entry.data.title} | 内容展馆群岛</title>
<meta name="description" content={entry.data.summary} />
</head>
<body>
<aside>
<h2>馆内目录</h2>
<ul>
{headings.map((item) => (
<li>
<a href={`#${item.slug}`}>{item.text}</a>
</li>
))}
</ul>
</aside>
<main>
<h1>{entry.data.title}</h1>
<p>{entry.data.summary}</p>
<Content />
</main>
</body>
</html>这里你要记住一条特别重要的规则:
在默认静态模式里,动态路由要在构建时提前列出所有可能路径
所以要写 getStaticPaths()而在按需服务端渲染的模式里,匹配到的路径可以请求时生成,不必都提前穷举。