跳到正文
Ggrryta
返回

Astro Content Collections 使用笔记

更新于:
约 1 分钟编辑本页

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>

几个坑

本文变更史


编辑本页
分享这篇文章:

下一篇
这个站点是怎么搭起来的