跳转到内容

内容集合 API 参考

新增于: astro@2.0.0

内容集合提供了用于在 src/content/ 目录中配置和查询 Markdown 或 MDX 文档的 API。有关功能和用法示例,请参阅我们的内容集合指南

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

类型: (input: CollectionConfig) => CollectionConfig

新增于: astro@2.0.0

defineCollection() 是一个在 src/content.config.* 文件中配置集合的工具函数。

src/content.config.ts
import { z, defineCollection } from 'astro:content';
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(),
}),
});
// Expose your defined collection to Astro
// with the `collections` export
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

schema 是一个可选的 Zod 对象,用于为一个集合配置文档 frontmatter 的类型和结构。每个值都必须使用Zod 验证器

有关示例用法,请参阅内容集合指南

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

添加于: astro@2.5.0

reference() 函数用于在内容配置中定义一个集合到另一个集合的关系,即“引用”。它接受一个集合名称,并将引用转换为一个包含集合名称和引用 ID 的对象。

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

import { defineCollection, reference, z } from 'astro:content';
import { glob, file } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/data/blog' }),
schema: z.object({
// Reference a single author from the `authors` collection by `id`
author: reference('authors'),
// Reference an array of related posts from the `blog` collection by `slug`
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
// if a referenced entry is invalid, this will return undefined.
const relatedPosts = await getEntries(blogPost.data.relatedPosts);

有关示例用法,请参阅内容集合指南

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

新增于: astro@2.0.0

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

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

---
import { getCollection } from 'astro:content';
// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatter
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
---

有关示例用法,请参阅内容集合指南

类型

  • (collection: string, id: string) => Promise<CollectionEntry<collection> | undefined>
  • ({ collection: string, id: string }) => Promise<CollectionEntry<collection> | undefined>
添加于: astro@2.5.0

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

---
import { getEntry } from 'astro:content';
// Get `src/content/blog/enterprise.md`
const enterprisePost = await getEntry('blog', 'enterprise');
// Get `src/content/captains/picard.json`
const picardProfile = await getEntry('captains', 'picard');
// Get the profile referenced by `data.captain`
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---

关于查询集合条目的示例,请参阅内容集合指南。

类型: (Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>

添加于: astro@2.5.0

getEntries() 是一个从同一个集合中检索多个集合条目的函数。这对于返回一个引用的条目数组以访问其关联的 databody 属性非常有用。

---
import { getEntries, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// Get related posts referenced by `data.relatedPosts`
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---

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

添加于: astro@5.0.0

一个用于编译给定条目以进行渲染的函数。它返回以下属性:

  • <Content /> - 一个用于在 Astro 文件中渲染文档内容的组件。
  • headings - 生成的标题列表,与 Astro 在 Markdown 和 MDX 导入中getHeadings() 工具函数类似。
  • remarkPluginFrontmatter - 在应用了任何 remark 或 rehype 插件后被修改的 frontmatter 对象。类型设置为 any
---
import { getEntry, render } from 'astro:content';
const entry = await getEntry('blog', 'entry-1');
if (!entry) {
// Handle Error, for example:
throw new Error('Could not find blog post 1');
}
const { Content, headings, remarkPluginFrontmatter } = await render(entry);
---

有关示例用法,请参阅内容集合指南

import type {
CollectionEntry,
CollectionKey,
ContentCollectionKey,
DataCollectionKey,
SchemaContext,
} from 'astro:content';

查询函数,包括 getCollection()getEntry()getEntries(),都返回类型为 CollectionEntry 的条目。此类型可作为 astro:content 的工具类型使用。

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

CollectionEntry 是一个泛型类型。将它与你正在查询的集合名称一起使用。例如,你的 blog 集合中的一个条目将具有 CollectionEntry<'blog'> 类型。

每个 CollectionEntry 都是一个包含以下值的对象:

类型: string

一个唯一的 ID。请注意,来自 Astro 内置 glob() 加载器的所有 ID 都经过了 slug 化处理。

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

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

类型: CollectionSchema<TCollectionName>

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

类型: string

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

添加于: astro@3.1.0

src/content.config.* 文件中定义的所有集合名称的字符串联合类型。在定义包装内置 getCollection() 的泛型函数时,此类型可能很有用。

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

defineCollection 用于 schema 函数形态的 context 对象。在为多个集合构建可重用的 schema 时,此类型可能很有用。

它包含以下属性:

import { defineCollection, z, type SchemaContext } from "astro:content";
export const imageSchema = ({ image }: SchemaContext) =>
z.object({
image: image(),
description: z.string().optional(),
});
const blog = defineCollection({
loader: /* ... */,
schema: ({ image }) => z.object({
title: z.string(),
permalink: z.string().optional(),
image: imageSchema({ image })
}),
});
贡献 社区 赞助