六维教程

Astro 页面与文件路由

文件即路由

Astro 使用「基于文件的路由」,src/pages/ 下的文件结构,直接决定网站的网址结构:

src/pages/
├── index.astro        ->  /
├── about.astro        ->  /about
├── blog/
│   ├── index.astro    ->  /blog
│   └── first.astro    ->  /blog/first

新建文件保存后,立刻就能在对应网址访问到,不需要任何路由配置。

页面文件类型

src/pages/ 里可以放这些类型的文件。

  • .astro 组件文件,最常见的页面。
  • .md / .mdx Markdown 文件,适合写文章。
  • .html 文件,会原样输出。
  • .js / .ts 结尾并导出页面的文件,用于动态生成。

页面结构

每个 .astro 页面由两部分组成,中间用 --- 代码栅栏隔开。

---
// 组件脚本:在这里写逻辑,不会出现在最终 HTML 里
const title = '我的页面';
---
<!-- 页面模板:这里写 HTML,会被渲染出来 -->
<html lang="zh-CN">
  <head><title>{title}</title></head>
  <body>
    <h1>{title}</h1>
  </body>
</html>

注意, --- 必须出现在文件最顶部,它把「逻辑」和「视图」清晰分开。

动态路由

如果你有一批结构相同、只是数据不同的页面(比如每篇文章一个页),可以用动态路由,文件名用方括号包住参数:

src/pages/blog/[slug].astro   ->  /blog/任意slug

在文件里通过 getStaticPaths 告诉 Astro 要生成哪些具体的网址。

---
// src/pages/blog/[slug].astro
const posts = [
  { slug: 'first', title: '第一篇' },
  { slug: 'second', title: '第二篇' },
];

// getStaticPaths 返回要生成的每个页面:params 是网址里的 [slug],props 是传给页面的数据
export async function getStaticPaths() {
  return posts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }));
}

const { post } = Astro.props; // Astro 是自动注入的全局对象(见 Astro 全局对象 /528),props 读取路由传入的数据
---
<h1>{post.title}</h1>

这种方式通常配合「内容集合」使用,后面章节(Astro 内容集合)会细讲。真实项目里文章数据多来自内容集合,第 18 篇再展开。

路由优先级

更具体的路径会覆盖更通用的动态路径,比如同时存在:

src/pages/blog/[slug].astro
src/pages/blog/about.astro

访问 /blog/about 会命中 about.astro,而不是动态规则。

404 页面

只要存在 src/pages/404.astro,Astro 就会把它作为找不到页面时的兜底页。

---
---
<html lang="zh-CN">
  <body>
    <h1>页面走丢了(404)</h1>
    <a href="/">返回首页</a>
  </body>
</html>
上一篇
Astro 常用命令
下一篇
Astro 页面导航与链接