Astro 內容集合
當您需要在 Astro 中建立或重構結構化內容時,請使用此技能,例如部落格、文件、更新日誌、案例研究、團隊資料或其他由綱要驅動的內容。
如果 astro-best-practices 可用,請與此技能一起套用,以獲得命名、可及性和效能方面的預設值。
工作流程
1. 決定該集合是建置時還是即時
大多數內容網站應使用 src/content.config.* 中的建置時集合。僅在資料真正需要在請求時即時更新時,才使用 src/live.config.* 中的即時集合。
在開始編碼前,請決定:
- 有哪些集合
- 哪些欄位是必填的
- 哪些關係需要參考
- 是否需要驗證圖片等資產
盡量採用能反映網站查詢內容方式的綱要,而不只是描述目前 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 工作流程 - 修正綱要不符之處,而不是削弱型別
- 為每個集合驗證至少一個真實條目
- 留意關於缺少載入器、舊版設定路徑或已棄用匯入的警告
遷移指南
當從舊版內容模式遷移時:
- 將
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。