Skip to content

内容集合 API 参考

Added in: astro@2.0.0

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

¥Content collections offer APIs to configure and query your Markdown or MDX documents in src/content/. For features and usage examples, see our content collections guide.

¥Imports from astro:content

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

类型:(input: CollectionConfig) => CollectionConfig

¥Type: (input: CollectionConfig) => CollectionConfig

Added in: astro@2.0.0

defineCollection() 是一个用于在 src/content.config.* 文件中配置集合的实用程序。

¥defineCollection() is a utility to configure a collection in a src/content.config.* file.

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 };

该函数接受以下属性:

¥This function accepts the following properties:

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

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

Added in: astro@5.0.0

loader 是一个对象或函数,允许你将数据从任何来源(本地或远程)加载到内容集合中。

¥A loader is either an object or a function that allows you to load data from any source, local or remote, into content collections.

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

¥Type: ZodType | (context: SchemaContext) => ZodType

Added in: astro@2.0.0

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

¥schema is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator.

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

¥Type: (collection: string) => ZodEffects<ZodString, { collection, id: string }>

Added in: astro@2.5.0

reference() 函数在内容配置中用于定义关系,或 “参考,” 从一个集合到另一个集合。这接受集合名称并验证内容 frontmatter 或数据文件中指定的条目标识符。

¥The reference() function is used in the content config to define a relationship, or “reference,” from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file.

此示例定义了博客作者对 authors 集合的引用以及对同一 blog 集合的相关帖子数组:

¥This example defines references from a blog author to the authors collection and an array of related posts to the same blog collection:

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 };

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

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

Added in: astro@2.0.0

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

¥getCollection() is a function that retrieves a list of content collection entries by collection name.

它默认返回集合中的所有项目,并接受可选的 filter 函数以按条目属性缩小范围。这允许你通过 data 对象根据 id 或 frontmatter 值仅查询集合中的某些项目。

¥It returns all items in the collection by default, and accepts an optional filter function to narrow by entry properties. This allows you to query for only some items in a collection based on id or frontmatter values via the data object.

---
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;
});
---

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

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

¥Type: ( collection: string, id: string ) => CollectionEntry<collection> | ({ collection: string, id: string }) => CollectionEntry<collection>

Added in: astro@2.5.0

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

¥getEntry() is a function that retrieves a single collection entry by collection name and the entry id. getEntry() can also be used to get referenced entries to access the data or body properties:

---
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);
---

有关 查询集合条目 的示例,请参阅 Content Collections 指南。

¥See the Content Collections guide for examples of querying collection entries.

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

¥Type: (Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>

Added in: astro@2.5.0

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

¥getEntries() is a function that retrieves multiple collection entries from the same collection. This is useful for returning an array of referenced entries to access their associated data and body properties.

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

类型:() => Promise<RenderedEntry>

¥Type: () => Promise<RenderedEntry>

Added in: astro@5.0.0

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

¥A function to compile a given entry for rendering. This returns the following properties:

---
import { getEntry, render } from 'astro:content';
const entry = await getEntry('blog', 'entry-1');
const { Content, headings, remarkPluginFrontmatter } = await render(entry);
---

请参阅 Content Collection 指南 例如用法。

¥See the Content Collection guide for example usage.

¥astro:content types

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

包括 getCollection()getEntry()getEntries() 在内的查询函数均返回 CollectionEntry 类型的条目。该类型可作为 astro:content 中的实用程序使用:

¥Query functions including getCollection(), getEntry(), and getEntries() each return entries with the CollectionEntry type. This type is available as a utility from astro:content:

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

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

¥CollectionEntry is a generic type. Use it with the name of the collection you’re querying. For example, an entry in your blog collection would have the type CollectionEntry<'blog'>.

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

¥Each CollectionEntry is an object with the following values:

示例类型:'author-1' | 'author-2' | ...

¥Example Type: 'author-1' | 'author-2' | ...

唯一 ID。请注意,Astro 内置 glob() 加载器中的所有 ID 都已 slugified。

¥A unique ID. Note that all IDs from Astro’s built-in glob() loader are slugified.

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

¥Example Type: 'blog' | 'authors' | ...

条目所在的集合的名称。这是用于在架构和查询函数中引用集合的名称。

¥The name of a collection in which entries are located. This is the name used to reference the collection in your schema, and in querying functions.

类型:CollectionSchema<TCollectionName>

¥Type: CollectionSchema<TCollectionName>

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

¥An object of frontmatter properties inferred from your collection schema (see defineCollection() reference). Defaults to any if no schema is configured.

类型:string

¥Type: string

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

¥A string containing the raw, uncompiled body of the Markdown or MDX document.

Added in: astro@3.1.0

src/content.config.* 文件中定义的所有集合名称的字符串并集。在定义接受任何集合名称的通用函数时,此类型非常有用。

¥A string union of all collection names defined in your src/content.config.* file. This type can be useful when defining a generic function that accepts any collection name.

import { type CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) {
return getCollection(collection);
}

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

¥The context object that defineCollection uses for the function shape of schema. This type can be useful when building reusable schemas for multiple collections.

这包括以下属性:

¥This includes the following property:

import 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 })
}),
});
Astro 中文网 - 粤ICP备13048890号