跳转到内容

内容集合 API 参考

添加于: astro@2.0.0

构建时内容集合提供 API 来配置、查询和渲染你的本地 Markdown、MDX、Markdoc、YAML、TOML 或 JSON 文件,以及远程内容。

添加于: astro@6.0.0

实时内容集合提供 API 来配置、查询和渲染来自远程源的最新实时数据。

有关功能和使用示例,请参阅我们的内容集合指南

import {
defineCollection,
defineLiveCollection,
getCollection,
getLiveCollection,
getEntry,
getLiveEntry,
getEntries,
reference,
render
} from 'astro:content';

类型: (input: CollectionConfig) => CollectionConfig

添加于: astro@2.0.0

用于在 src/content.config.* 文件中配置集合的工具函数。

src/content.config.ts
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 };

此函数接受以下属性:

类型: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader

添加于: astro@5.0.0

一个对象或函数,允许你将来自本地或远程任何来源的数据加载到构建时内容集合中。(对于实时集合,请参阅 实时 loader 属性。)

通过引导式解释和示例用法了解 构建时集合加载器

类型: ZodType | (context: SchemaContext) => ZodType

添加于: astro@2.0.0

一个可选的 Zod 对象或返回 Zod 对象的函数,用于配置集合中文档 frontmatter 的类型和结构。每个值必须使用 Zod 验证器 (EN)。(对于实时集合,请参阅 实时 schema 属性。)

通过引导式解释、示例用法和常用数据类型了解如何使用 Zod 来 定义集合模式

类型: (config: LiveCollectionConfig) => LiveCollectionConfig

添加于: astro@6.0.0

一个用于在 src/live.config.* 文件中配置实时集合的工具函数。

src/live.config.ts
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 };

此函数接受以下属性:

类型: LiveLoader

添加于: astro@6.0.0

一个允许你在运行时从远程源将数据加载到实时内容集合中的对象。(对于构建时集合,请参阅 构建时 loader 属性。)

通过引导式讲解和示例用法了解如何 创建实时加载器

类型: ZodType

添加于: astro@6.0.0

一个可选的 Zod 对象,用于为实时集合配置数据的类型和结构。每个值都必须使用 Zod 验证器。(对于构建时集合,请参阅 构建时 schema 属性。)

当你定义一个模式时,在查询集合时,它将优先于 实时加载器的类型

通过引导式讲解和使用示例,了解如何 在实时集合中使用 Zod 模式

类型: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>

添加于: astro@2.5.0

一种在内容配置中用于定义集合间关系或 “引用” 的函数。该函数接收集合名称,并将引用转换为包含集合名称和引用 ID 的对象。

此示例定义了从博客作者到 authors 集合的引用,以及一个指向同一 blog 集合的相关文章数组的引用:

src/content.config.ts
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() 时会在运行时进行验证。

src/pages/[posts].astro
// 如果引用的条目无效,将返回 undefined。
const relatedPosts = await getEntries(blogPost.data.relatedPosts);
通过引导式解释和使用示例学习如何 定义和使用集合引用

类型: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]

添加于: astro@2.0.0

一个通过集合名称检索内容集合条目列表的函数。

默认情况下,它返回集合中的所有条目,并接受一个可选的 filter 函数来根据条目属性缩小范围。这允许你基于 id 或通过 data 对象中的 frontmatter 值来查询集合中的部分条目。

src/pages/blog/index.astro
---
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;
});
---
通过引导式解释和使用示例学习如何 查询构建时集合

类型: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>

添加于: astro@6.0.0

一个通过集合名称获取实时内容集合条目列表的函数。

该函数默认返回集合中的所有条目,并接受一个可选的 filter 对象,其结构由集合的加载器定义。这允许你根据 API 的功能,仅查询集合中的部分条目或以不同形式检索数据。

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
// 从你的 API 获取全部 `products` 条目
const { entries: allProducts } = await getLiveCollection('products');
// 仅返回被精选的 `products`
const { entries: featuredProducts } = await getLiveCollection('products', { featured: true });
---
通过引导式解释和使用示例学习如何 访问实时集合数据

类型:

添加于: astro@2.5.0

一个通过集合名称和条目 id 检索单个集合条目的函数。getEntry() 也可用于获取引用的条目以访问 databody 属性:

src/pages/index.astro
---
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);
---
通过引导式解释和使用示例学习更多关于 查询构建时集合 的内容。

类型: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>

添加于: astro@6.0.0

一个通过集合名称和可选筛选器(可以是 id 字符串或类型安全对象)来检索单个实时集合条目的函数。

src/pages/blog/[id].astro
---
import { getLiveEntry } from 'astro:content';
const { entry: liveCollectionsPost } = await getLiveEntry('blog', Astro.params.id);
const { entry: mattDraft } = await getLiveEntry('blog', {
status: 'draft',
author: 'matt',
});
---
通过引导式解释和使用示例学习如何 访问实时集合数据

类型: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]

添加于: astro@2.5.0

一个从同一集合中检索多个集合条目的函数。这有助于 返回引用条目的数组,以访问其关联的 databody 属性。

src/pages/blog/enterprise/index.astro
---
import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// 获取由 `data.relatedPosts` 引用的相关文章
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

类型: (entry: CollectionEntry) => Promise<RenderResult>

添加于: astro@5.0.0

一个用于编译指定条目以供渲染的函数。该函数返回以下属性:

  • <Content /> - 一个用于在 Astro 文件中渲染文档内容的组件。
  • headings - 一个生成的标题列表,与 Astro 的 getHeadings() 工具函数 在 Markdown 和 MDX 导入中的功能一致。
  • remarkPluginFrontmatter - 经过任何 remark 或 rehype 插件处理 后修改过的 frontmatter 对象。设置为 any 类型。
src/pages/blog/entry-1.astro
---
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);
---
通过引导式解释和使用示例学习如何 渲染条目的正文内容
import type {
CollectionEntry,
CollectionKey,
SchemaContext,
} from 'astro:content';

包括 getCollection()getEntry()getEntries() 在内的查询函数均返回具有 CollectionEntry 类型的条目。该类型可作为工具类型从 astro:content 导入:

import type { CollectionEntry } from 'astro:content';

一种泛型类型,用于表示你正在查询的集合中的单个条目,使用时需指定集合名称。例如,blog 集合中的一个条目将具有类型 CollectionEntry<'blog'>>。

每个 CollectionEntry 都是一个具有以下值的对象:

类型: string

一个唯一的 ID。请注意,所有来自 Astro 内置 glob() 加载器的 ID 都会被转换为 slug 格式。

类型: CollectionKey

条目所在集合的名称。这是在你的模式和查询函数中用于引用该集合的名称。

类型: CollectionSchema<TCollectionName>

从你的集合模式推断出的 frontmatter 属性对象(参见 defineCollection() 参考文档)。如果未配置模式,则默认为 any

类型: string | undefined

一个包含 Markdown 或 MDX 文档原始未编译正文内容的字符串。

请注意,如果 retainBody 设置为 false,此值将为 undefined,而不是包含原始文件内容。

类型: RenderedContent | undefined

由加载器存储 的条目的渲染内容。例如,这可以是 Markdown 条目的渲染内容,或来自 CMS 的 HTML。

类型: string | undefined

相对于项目目录的条目路径。此值仅适用于本地条目。

示例类型: 'blog' | 'authors' | ...

添加于: astro@3.1.0

在你的 src/content.config.* 文件中定义的所有集合名称的字符串联合类型。当定义一个封装内置 getCollection() 的通用函数时,该类型会非常有用。

src/utils/collections.ts
import { type CollectionKey, getCollection } from 'astro:content';
export async function queryCollection(collection: CollectionKey) {
return getCollection(collection, ({ data }) => {
return data.draft !== true;
});
}

defineCollection 用于 schema 函数形式的 context 对象。该类型在为多个集合构建可复用的 schema 时非常有用。

包含以下属性:

src/content.config.ts
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 })
}),
});
import type {
LiveDataCollectionResult,
LiveDataEntryResult,
} from "astro";

类型: { entries?: Array<LiveDataEntry<TData>>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }

添加于: astro@6.0.0

getLiveCollection() 返回的对象,包含由实时加载器获取的数据。它具有以下属性:

类型: Array<LiveDataEntry<TData>> | undefined

由加载器返回的 LiveDataEntry 对象数组。

以下示例访问名为 products 的实时集合所返回的条目:

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
const { entries: allProducts } = await getLiveCollection('products');
---
通过引导式解释和使用示例学习如何 访问实时集合数据

类型: TError | LiveCollectionError | undefined

加载器加载集合失败时返回的错误。这可以是由加载器定义的自定义错误,也可以是内置错误。

以下示例访问从名为 products 的实时集合中检索数据时返回的错误:

src/pages/shop/index.astro
---
import { getLiveCollection } from 'astro:content';
const { error } = await getLiveCollection('products');
---
通过引导式解释和使用示例学习更多关于 错误处理 的内容。

类型: CacheHint | undefined

一个提供用于指导缓存策略的数据的对象。

如果你启用了 实验性路由缓存 (EN) ,请将缓存提示直接传递给 Astro.cache.set()

src/pages/shop/index.astro
---
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 });
---

你也可以使用缓存提示手动设置响应头:

src/pages/shop/index.astro
---
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());
}
---

类型: { entry?: LiveDataEntry<TData>; error?: TError | LiveCollectionError; cacheHint?: CacheHint; }

添加于: astro@6.0.0

getLiveEntry() 返回的对象,包含由实时加载器获取的数据。它具有以下属性:

类型: LiveDataEntry<TData> | undefined

由加载器返回的 LiveDataEntry 对象。

以下示例访问名为 products 的实时集合中请求的条目:

src/pages/shop/[id].astro
---
import { getLiveEntry } from 'astro:content';
const { entry } = await getLiveEntry('products', Astro.params.id);
---
通过引导式解释和使用示例学习如何 访问实时集合数据

类型: TError | LiveCollectionError | undefined

当加载器加载条目失败时返回的错误。这可以是由加载器定义的自定义错误,也可以是内置错误。

以下示例访问名为 products 的实时集合中请求的条目及任何错误,并在存在错误时重定向到 404 页面:

src/pages/shop/[id].astro
---
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>
通过引导式解释和使用示例学习更多关于 错误处理 的内容。

类型: CacheHint | undefined

一个提供用于指导缓存策略的数据的对象。

如果你启用了 实验性路由缓存 (EN) ,请将缓存提示直接传递给 Astro.cache.set()

src/pages/shop/[id].astro
---
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 });
---

你也可以使用缓存提示手动设置响应头:

src/pages/shop/[id].astro
---
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());
}
---
贡献 社区 赞助