使用 Astro 内容集合管理文章
在 Astro 中,src/content/ 目录下的 Markdown 文件会由内容集合统一管理。Fluid for Astro 定义了两个集合:
posts:博客文章,位于src/content/posts/pages:独立页面,位于src/content/pages/
创建一篇文章
在 src/content/posts/ 下新建任意 .md 文件:
---
title: 使用 Astro 内容集合管理文章
date: 2026-10-18T20:15:00+08:00
updated: 2026-10-19T09:00:00+08:00
description: 一段用于 SEO 与首页摘要的描述。
categories: [技术, Astro]
tags: [Astro, 内容集合]
indexImg: /img/fluid.png
sticky: 0
categoryBar: true
---
正文从这里开始。
文件名会成为文章 URL 的一部分。例如 src/content/posts/hello-fluid.md 对应 /posts/hello-fluid/。
Front matter 字段
| 字段 | 类型 | 说明 |
|---|---|---|
title | string | 文章标题,必填 |
date | Date | 发布时间,必填 |
updated | Date | 更新时间,可选 |
description | string | 摘要,用于首页、SEO 与 RSS |
categories | string[] | 分类链,例如 [技术, Astro] |
tags | string[] | 标签列表 |
indexImg | string | 首页封面图 |
bannerImg | string | 文章页头图,覆盖默认值 |
bannerImgHeight | number | 头图高度(0–100,单位 vh) |
bannerMaskAlpha | number | 头图遮罩透明度(0–1) |
sticky | number | 置顶权重,越大越靠前 |
hide | boolean | 从首页和归档中隐藏,但仍生成文章页 |
archive | boolean | 仅从首页隐藏 |
draft | boolean | 草稿,生产构建时排除 |
toc | boolean | 是否显示目录 |
categoryBar | boolean | string[] | 是否显示分类侧栏 |
copyright | boolean | string | 是否显示版权声明,或指定协议 |
comments | boolean | 是否显示评论 |
math | boolean | 是否包含公式 |
mermaid | boolean | 是否包含 Mermaid 图表 |
所有字段都有默认值,除了 title 与 date 之外都可以省略。
类型安全
集合的 schema 定义在 src/content/config.ts:
const postsCollection = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
date: z.coerce.date(),
description: z.string().optional().default(""),
categories: z.array(z.string()).optional().default([]),
tags: z.array(z.string()).optional().default([]),
// ...
}),
});
如果 front matter 写错了类型,例如把 tags 写成字符串,astro check 与构建都会给出明确提示。
分类与标签
分类是一个层级链。categories: [技术, Astro] 会生成:
/categories/技术//categories/技术/astro/
文章会同时出现在父分类与子分类的列表中,分类页展示当前分类及其子分类下的全部文章。
标签则是扁平列表,每个标签对应 /tags/<slug>/。
页面
独立页面放在 src/content/pages/。例如 about.md 会被 /about/ 页面读取并渲染,其他页面会自动生成到 /<slug>/。
---
title: 关于
description: 关于这个博客
comments: false
---
页面正文。
草稿与隐藏
draft: true:开发环境可见,生产构建排除。hide: true:不进入首页、归档、分类、标签与搜索,但文章页仍然可以访问。archive: true:只从首页隐藏,仍会出现在归档中。
小结
内容集合让「写作」和「主题代码」彻底分离。你只需要关心 Markdown 与 front matter,剩下的路由、摘要、字数、搜索索引都会在构建时自动完成。
使用 Astro 内容集合管理文章
https://fluid-astro.example.com/posts/astro-content/