内容集合 API 参考
添加于:
astro@2.0.0
构建时内容集合提供 API 来配置、查询和渲染你的本地 Markdown、MDX、Markdoc、YAML、TOML 或 JSON 文件,以及远程内容。
添加于:
astro@6.0.0
实时内容集合提供 API 来配置、查询和渲染来自远程源的最新实时数据。
有关功能和使用示例,请参阅我们的内容集合指南。
从 astro:content 导入
Section titled “从 astro:content 导入”import { defineCollection, defineLiveCollection, getCollection, getLiveCollection, getEntry, getLiveEntry, getEntries, reference, render} from 'astro:content';defineCollection()
Section titled “defineCollection()”类型: (input: CollectionConfig) => CollectionConfig
astro@2.0.0
用于在 src/content.config.* 文件中配置集合的工具函数。
import { defineCollection } from 'astro:content';import { z } from 'astro/zod';import { glob } from 'astro/loaders';
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: z.object({ title: z.string(), permalink: z.string().optional(), }),});
// 将你定义的集合暴露给 Astro// 通过 `collections` 导出export const collections = { blog };此函数接受以下属性:
loader
Section titled “loader”类型: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader
astro@5.0.0
一个对象或函数,允许你将来自本地或远程任何来源的数据加载到构建时内容集合中。(对于实时集合,请参阅 实时 loader 属性。)
schema
Section titled “schema”类型: ZodType | (context: SchemaContext) => ZodType
astro@2.0.0
一个可选的 Zod 对象或返回 Zod 对象的函数,用于配置集合中文档 frontmatter 的类型和结构。每个值必须使用 Zod 验证器 (EN)。(对于实时集合,请参阅 实时 schema 属性。)
defineLiveCollection()
Section titled “defineLiveCollection()”类型: (config: LiveCollectionConfig) => LiveCollectionConfig
astro@6.0.0
一个用于在 src/live.config.* 文件中配置实时集合的工具函数。
import { defineLiveCollection } from 'astro:content';import { storeLoader } from '@example/astro-loader';
const products = defineLiveCollection({ loader: storeLoader({ apiKey: process.env.STORE_API_KEY, endpoint: 'https://api.example.com/v1', }),});
// 将你定义的集合暴露给 Astro// 通过 `collections` 导出export const collections = { products };此函数接受以下属性:
loader
Section titled “loader”类型: LiveLoader
astro@6.0.0
一个允许你在运行时从远程源将数据加载到实时内容集合中的对象。(对于构建时集合,请参阅 构建时 loader 属性。)
schema
Section titled “schema”类型: ZodType
astro@6.0.0
一个可选的 Zod 对象,用于为实时集合配置数据的类型和结构。每个值都必须使用 Zod 验证器。(对于构建时集合,请参阅 构建时 schema 属性。)
当你定义一个模式时,在查询集合时,它将优先于 实时加载器的类型。
reference()
Section titled “reference()”类型: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>
astro@2.5.0
一种在内容配置中用于定义集合间关系或 “引用” 的函数。该函数接收集合名称,并将引用转换为包含集合名称和引用 ID 的对象。
此示例定义了从博客作者到 authors 集合的引用,以及一个指向同一 blog 集合的相关文章数组的引用:
import { defineCollection, reference } from 'astro:content';import { z } from 'astro/zod';import { glob, file } from 'astro/loaders';
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: z.object({ // 通过 `id` 从 `authors` 集合中引用单个作者 author: reference('authors'), // 通过 `slug` 从 `blog` 集合中引用相关文章的数组。 relatedPosts: z.array(reference('blog')), })});
const authors = defineCollection({ loader: file("src/data/authors.json"), schema: z.object({ /* ... */ })});
export const collections = { blog, authors };引用的条目在使用 getEntry() 或 getEntries() 时会在运行时进行验证。
// 如果引用的条目无效,将返回 undefined。const relatedPosts = await getEntries(blogPost.data.relatedPosts);getCollection()
Section titled “getCollection()”类型: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]
astro@2.0.0
一个通过集合名称检索内容集合条目列表的函数。
默认情况下,它返回集合中的所有条目,并接受一个可选的 filter 函数来根据条目属性缩小范围。这允许你基于 id 或通过 data 对象中的 frontmatter 值来查询集合中的部分条目。
---import { getCollection } from 'astro:content';
// 获取全部的 `src/data/blog/` 条目const allBlogPosts = await getCollection('blog');
// 仅返回在 frontmatter 中 `draft: true` 的文章const draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});---getLiveCollection()
Section titled “getLiveCollection()”类型: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>
astro@6.0.0
一个通过集合名称获取实时内容集合条目列表的函数。
该函数默认返回集合中的所有条目,并接受一个可选的 filter 对象,其结构由集合的加载器定义。这允许你根据 API 的功能,仅查询集合中的部分条目或以不同形式检索数据。
---import { getLiveCollection } from 'astro:content';
// 从你的 API 获取全部 `products` 条目const { entries: allProducts } = await getLiveCollection('products');
// 仅返回被精选的 `products`const { entries: featuredProducts } = await getLiveCollection('products', { featured: true });---getEntry()
Section titled “getEntry()”类型:
-
(collection: CollectionKey, id: string) => Promise<CollectionEntry | undefined> -
({ collection: CollectionKey, id: string }) => Promise<CollectionEntry | undefined>
astro@2.5.0
一个通过集合名称和条目 id 检索单个集合条目的函数。getEntry() 也可用于获取引用的条目以访问 data 或 body 属性:
---import { getEntry } from 'astro:content';
// 获取 `src/content/blog/enterprise.md`const enterprisePost = await getEntry('blog', 'enterprise');
// 获取 `src/content/captains/picard.json`const picardProfile = await getEntry('captains', 'picard');
// 获取由 `data.captain` 引用的个人资料const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);---getLiveEntry()
Section titled “getLiveEntry()”类型: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>
astro@6.0.0
一个通过集合名称和可选筛选器(可以是 id 字符串或类型安全对象)来检索单个实时集合条目的函数。
---import { getLiveEntry } from 'astro:content';
const { entry: liveCollectionsPost } = await getLiveEntry('blog', Astro.params.id);const { entry: mattDraft } = await getLiveEntry('blog', { status: 'draft', author: 'matt',});---getEntries()
Section titled “getEntries()”类型: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]
astro@2.5.0
一个从同一集合中检索多个集合条目的函数。这有助于 返回引用条目的数组,以访问其关联的 data 和 body 属性。
---import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// 获取由 `data.relatedPosts` 引用的相关文章const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);---render()
Section titled “render()”类型: (entry: CollectionEntry) => Promise<RenderResult>
astro@5.0.0
一个用于编译指定条目以供渲染的函数。该函数返回以下属性:
<Content />- 一个用于在 Astro 文件中渲染文档内容的组件。headings- 一个生成的标题列表,与 Astro 的getHeadings()工具函数 在 Markdown 和 MDX 导入中的功能一致。remarkPluginFrontmatter- 经过任何 remark 或 rehype 插件处理 后修改过的 frontmatter 对象。设置为any类型。
---import { getEntry, render } from 'astro:content';const entry = await getEntry('blog', 'entry-1');
if (!entry) { // 处理错误,比如: throw new Error('Could not find blog post 1');}const { Content, headings, remarkPluginFrontmatter } = await render(entry);---astro:content 类型
Section titled “astro:content 类型”import type { CollectionEntry, CollectionKey, SchemaContext,} from 'astro:content';CollectionEntry
Section titled “CollectionEntry”包括 getCollection()、getEntry() 和 getEntries() 在内的查询函数均返回具有 CollectionEntry 类型的条目。该类型可作为工具类型从 astro:content 导入:
import type { CollectionEntry } from 'astro:content';一种泛型类型,用于表示你正在查询的集合中的单个条目,使用时需指定集合名称。例如,blog 集合中的一个条目将具有类型 CollectionEntry<'blog'>>。
每个 CollectionEntry 都是一个具有以下值的对象:
CollectionEntry.id
Section titled “CollectionEntry.id”类型: string
一个唯一的 ID。请注意,所有来自 Astro 内置 glob() 加载器的 ID 都会被转换为 slug 格式。
CollectionEntry.collection
Section titled “CollectionEntry.collection”类型: CollectionKey
条目所在集合的名称。这是在你的模式和查询函数中用于引用该集合的名称。
CollectionEntry.data
Section titled “CollectionEntry.data”类型: CollectionSchema<TCollectionName>
从你的集合模式推断出的 frontmatter 属性对象(参见 defineCollection() 参考文档)。如果未配置模式,则默认为 any。
CollectionEntry.body
Section titled “CollectionEntry.body”类型: string | undefined
一个包含 Markdown 或 MDX 文档原始未编译正文内容的字符串。
请注意,如果 retainBody 设置为 false,此值将为 undefined,而不是包含原始文件内容。
CollectionEntry.rendered
Section titled “CollectionEntry.rendered”类型: RenderedContent | undefined
由加载器存储 的条目的渲染内容。例如,这可以是 Markdown 条目的渲染内容,或来自 CMS 的 HTML。
CollectionEntry.filePath
Section titled “CollectionEntry.filePath”类型: string | undefined
相对于项目目录的条目路径。此值仅适用于本地条目。
CollectionKey
Section titled “CollectionKey”示例类型: 'blog' | 'authors' | ...
astro@3.1.0
在你的 src/content.config.* 文件中定义的所有集合名称的字符串联合类型。当定义一个封装内置 getCollection() 的通用函数时,该类型会非常有用。
import { type CollectionKey, getCollection } from 'astro:content';
export async function queryCollection(collection: CollectionKey) { return getCollection(collection, ({ data }) => { return data.draft !== true; });}SchemaContext
Section titled “SchemaContext”defineCollection 用于 schema 函数形式的 context 对象。该类型在为多个集合构建可复用的 schema 时非常有用。
包含以下属性:
image-image()模式助手,允许你 在内容集合中使用本地图片
import { defineCollection, type SchemaContext } from "astro:content";import { z } from 'astro/zod';import { glob } from 'astro/loaders';
export const imageSchema = ({ image }: SchemaContext) => z.object({ image: image(), description: z.string().optional(), });
const blog = defineCollection({ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }), schema: ({ image }) => z.object({ title: z.string(), permalink: z.string().optional(), image: imageSchema({ image }) }),});astro 类型
Section titled “astro 类型”import type { LiveDataCollectionResult, LiveDataEntryResult,} from "astro";LiveDataCollectionResult
Section titled “LiveDataCollectionResult”类型: { entries?: Array<LiveDataEntry<TData>>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }
astro@6.0.0
由 getLiveCollection() 返回的对象,包含由实时加载器获取的数据。它具有以下属性:
LiveDataCollectionResult.entries
Section titled “LiveDataCollectionResult.entries”类型: Array<LiveDataEntry<TData>> | undefined
由加载器返回的 LiveDataEntry 对象数组。
以下示例访问名为 products 的实时集合所返回的条目:
---import { getLiveCollection } from 'astro:content';
const { entries: allProducts } = await getLiveCollection('products');---LiveDataCollectionResult.error
Section titled “LiveDataCollectionResult.error”类型: TError | LiveCollectionError | undefined
加载器加载集合失败时返回的错误。这可以是由加载器定义的自定义错误,也可以是内置错误。
以下示例访问从名为 products 的实时集合中检索数据时返回的错误:
---import { getLiveCollection } from 'astro:content';
const { error } = await getLiveCollection('products');---LiveDataCollectionResult.cacheHint
Section titled “LiveDataCollectionResult.cacheHint”类型: CacheHint | undefined
一个提供用于指导缓存策略的数据的对象。
如果你启用了 实验性路由缓存 (EN) ,请将缓存提示直接传递给 Astro.cache.set():
---import { getLiveCollection } from 'astro:content';export const prerender = false; // 无需 'server' 模式
const { cacheHint } = await getLiveCollection('products');
if (cacheHint) { Astro.cache.set(cacheHint);}Astro.cache.set({ maxAge: 600 });---你也可以使用缓存提示手动设置响应头:
---import { getLiveCollection } from 'astro:content';
const { cacheHint } = await getLiveCollection('products');
if (cacheHint?.tags) { Astro.response.headers.set('Cache-Tag', cacheHint.tags.join(','));}if (cacheHint?.lastModified) { Astro.response.headers.set('Last-Modified', cacheHint.lastModified.toUTCString());}---LiveDataEntryResult
Section titled “LiveDataEntryResult”类型: { entry?: LiveDataEntry<TData>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }
astro@6.0.0
由 getLiveEntry() 返回的对象,包含由实时加载器获取的数据。它具有以下属性:
LiveDataEntryResult.entry
Section titled “LiveDataEntryResult.entry”类型: LiveDataEntry<TData> | undefined
由加载器返回的 LiveDataEntry 对象。
以下示例访问名为 products 的实时集合中请求的条目:
---import { getLiveEntry } from 'astro:content';
const { entry } = await getLiveEntry('products', Astro.params.id);---LiveDataEntryResult.error
Section titled “LiveDataEntryResult.error”类型: TError | LiveCollectionError | undefined
当加载器加载条目失败时返回的错误。这可以是由加载器定义的自定义错误,也可以是内置错误。
以下示例访问名为 products 的实时集合中请求的条目及任何错误,并在存在错误时重定向到 404 页面:
---import { getLiveEntry } from 'astro:content';
const { entry, error } = await getLiveEntry('products', Astro.params.id);
if (error) { return Astro.redirect('/404');}---<h1>{entry.data.name}</h1>LiveDataEntryResult.cacheHint
Section titled “LiveDataEntryResult.cacheHint”类型: CacheHint | undefined
一个提供用于指导缓存策略的数据的对象。
如果你启用了 实验性路由缓存 (EN) ,请将缓存提示直接传递给 Astro.cache.set():
---import { getLiveEntry } from 'astro:content';
export const prerender = false; // Not needed in 'server' mode
const { cacheHint } = await getLiveEntry('products', Astro.params.id);
if (cacheHint) { Astro.cache.set(cacheHint);}Astro.cache.set({ maxAge: 300 });---你也可以使用缓存提示手动设置响应头:
---import { getLiveEntry } from 'astro:content';
const { cacheHint } = await getLiveEntry('products', Astro.params.id);
if (cacheHint?.tags) { Astro.response.headers.set('Cache-Tag', cacheHint.tags.join(','));}if (cacheHint?.lastModified) { Astro.response.headers.set('Last-Modified', cacheHint.lastModified.toUTCString());}---