Astro 内容集合
在创建或重构 Astro 中的结构化内容时使用此技能,例如博客、文档、更新日志、案例研究、团队数据或其他基于 schema 的内容。
如果 astro-best-practices 可用,请将此技能与之一同应用,以获得命名、可访问性和性能方面的默认设置。
工作流程
1. 决定集合是构建时还是实时
大多数内容网站应使用 src/content.config.* 中的构建时集合。仅当数据确实需要请求时的新鲜度时,才在 src/live.config.* 中使用实时集合。
在编码之前,请决定:
- 存在哪些集合
- 哪些字段是必需的
- 哪些关系需要引用
- 是否应验证图像等资源
优先使用反映站点如何查询内容的 schema,而不仅仅是 frontmatter 当前的样子。
2. 在 src/content.config.* 中定义集合
使用当前的 Content Layer API。对于构建时集合:
- 在
src/content.config.ts(或.js/.mjs)中定义它们 - 为每个集合提供一个
loader - 从
astro/zod导入z - 不要使用
type: 'content'或type: 'data'
示例:
import { defineCollection, reference } from 'astro:content'
import { glob } from 'astro/loaders'
import { z } from 'astro/zod'
const blog = defineCollection({
loader: glob({ base: './src/content/blog', pattern: '**/*.{md,mdx}' }),
schema: ({ image }) => z.object({
title: z.string(),
description: z.string(),
publishDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
author: reference('authors'),
cover: image().optional(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
}),
})
const authors = defineCollection({
loader: glob({ base: './src/data/authors', pattern: '**/*.json' }),
schema: z.object({
name: z.string(),
email: z.email().optional(),
avatar: z.url().optional(),
}),
})
export const collections = { blog, authors }
有用的模式:
glob()用于本地条目文件夹file()用于单个 JSON 或其他数据文件z.enum(...)用于受控值z.coerce.date()用于 frontmatter 日期reference('collection-name')用于关系- 当图像验证很重要时,使用
schema: ({ image }) => ...
3. 保持集合形状最新
对于 Astro 6 及更新版本:
- 使用
src/content.config.*,而不是src/content/config.* - 使用
entry.id作为 URL 和查询中的类似 slug 的标识符 - 仅当真正需要源路径时才使用
entry.filePath - 使用
getEntry()代替旧的getEntryBySlug()或getDataEntryById()
优先使用稳定的文件夹结构和可预测的 ID。如果内容在逻辑上是一个集合,则避免将其分散到路由文件夹中。
4. 有目的地查询
使用与任务匹配的内容 API:
getCollection()用于列表getEntry()用于单个已知条目getEntries()用于引用数组- 集合过滤器用于草稿/已发布分割
示例:
---
import { getCollection } from 'astro:content'
const posts = await getCollection('blog', ({ data }) => !data.draft)
---
渲染条目时,保持路由生成和内容渲染足够分离,以便每个部分易于理解。
5. 使用当前 API 连接路由和渲染
对于动态路由:
- 从集合 ID 构建路径
- 通过 props 干净地传递条目
- 使用
render(entry)渲染内容
示例:
---
import { getCollection, render } from 'astro:content'
export async function getStaticPaths() {
const posts = await getCollection('blog')
return posts.map((post) => ({
params: { slug: post.id },
props: { post },
}))
}
const { post } = Astro.props
const { Content } = await render(post)
---
<article>
<h1>{post.data.title}</h1>
<Content />
</article>
6. 同步和验证
更改集合后:
- 运行
npx astro sync或仓库的正常 Astro 工作流程 - 修复 schema 不匹配,而不是削弱类型
- 验证每个集合至少有一个真实条目
- 注意有关缺少加载器、旧版配置路径或已弃用导入的警告
迁移指南
从旧版内容模式迁移时:
- 将
src/content/config.ts移动到src/content.config.ts - 为每个集合添加一个
loader - 移除任何
type: 'content'或type: 'data' - 将
import { defineCollection, z } from 'astro:content'替换为import { defineCollection } from 'astro:content'和import { z } from 'astro/zod' - 将
post.slug替换为post.id - 将
entry.render()替换为render(entry) - 将
getEntryBySlug()和getDataEntryById()替换为getEntry()
如果项目同时跨越 Astro 版本,请在定稿前在当前的官方 Astro 文档中验证版本敏感的内容 API。