Content Collections 是 Astro 里我最喜欢的部分:它把散落的 Markdown 变成类型安全的数据源。本站的搭建过程记在 这个站点是怎么搭起来的 里,用的就是这套东西。
定义
在 src/content.config.ts 里声明 collection,用 Zod 描述字段。写错字段名或者漏了必填项,构建时直接报错,而不是等到页面上出现 undefined。
查询
import { getCollection } from 'astro:content';
const posts = await getCollection('posts', ({ data }) => !data.draft);
第二个参数是过滤器,draft: true 的文章不会出现在正式构建里,适合存半成品。
渲染
详情页里拿到 entry 之后调用 render(),再用 <Content /> 组件输出正文:
---
const { post } = Astro.props;
const { Content } = await render(post);
---
<article><Content /></article>
几个坑
- 条目排序要自己做,
getCollection不保证顺序,按发布日期排一遍最稳妥。 entry.id是相对 base 目录的路径(不含扩展名),有子目录时会带/。- 标签去重别用嵌套循环,
Set一行搞定。