콘텐츠 컬렉션 API 참조
Added in:
astro@2.0.0
콘텐츠 컬렉션은 src/content/
에서 Markdown 또는 MDX 문서를 구성하고 쿼리하는 API를 제공합니다. 기능 및 사용 예시는 콘텐츠 컬렉션 가이드를 참조하세요.
astro:content
에서 가져오기
섹션 제목: astro:content에서 가져오기import { z, defineCollection, getCollection, getEntry, getEntries, reference, } from 'astro:content';
defineCollection()
섹션 제목: defineCollection()타입: (input: CollectionConfig) => CollectionConfig
astro@2.0.0
defineCollection()
은 src/content.config.*
파일에 컬렉션을 구성하는 유틸리티입니다.
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(), }),});
// `collections` 내보내기를 통해 정의된 컬렉션을 Astro에 노출합니다.export const collections = { blog };
이 함수는 다음 속성을 허용합니다.
loader
섹션 제목: loader타입: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader
astro@5.0.0
loader
는 로컬 또는 원격 소스에서 콘텐츠 컬렉션으로 데이터를 로드할 수 있게 해주는 객체 또는 함수입니다.
예시 사용법은 콘텐츠 컬렉션
가이드를 참조하세요.
schema
섹션 제목: schema타입: ZodType | (context: SchemaContext) => ZodType
astro@2.0.0
schema
는 컬렉션에 대한 문서 프런트매터의 타입과 모양을 구성하는 선택적 Zod 객체입니다. 각 값은 Zod 유효성 검사기를 사용해야 합니다.
사용 예시는 콘텐츠 컬렉션
가이드를 참조하세요.
reference()
섹션 제목: reference()타입: (collection: string) => ZodEffects<ZodString, { collection, id: string }>
astro@2.5.0
reference()
함수는 콘텐츠 구성에서 한 컬렉션에서 다른 컬렉션으로의 관계 또는 “reference”를 정의하는 데 사용됩니다. 이는 컬렉션 이름을 전달받고 콘텐츠 프런트매터 또는 데이터 파일에 지정된 항목 식별자의 유효성을 검사합니다.
이 예시에서는 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({ // `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 };
사용 예시는 콘텐츠 컬렉션
가이드를 참조하세요.
getCollection()
섹션 제목: getCollection()타입: (collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]
astro@2.0.0
getCollection()
은 컬렉션 이름별로 콘텐츠 컬렉션 항목 목록을 검색하는 함수입니다.
기본적으로 컬렉션의 모든 항목을 반환하고 항목 속성별로 범위를 좁힐 수 있는 선택적 filter
함수를 허용합니다. 이를 통해 data
객체를 통해 id
또는 프런트매터 값을 기반으로 컬렉션의 일부 항목만 쿼리할 수 있습니다.
---import { getCollection } from 'astro:content';
// 모든 `src/content/blog/` 항목을 가져옵니다.const allBlogPosts = await getCollection('blog');
// 프런트매터에 `draft: true`가 포함된 게시물만 반환합니다.const draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});---
사용 예시는 콘텐츠 컬렉션
가이드를 참조하세요.
getEntry()
섹션 제목: getEntry()타입:
(collection: string, id: string) => Promise<CollectionEntry<collection> | undefined>
({ collection: string, id: string }) => Promise<CollectionEntry<collection> | undefined>
astro@2.5.0
getEntry()
는 컬렉션 이름과 항목 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);---
컬렉션 항목 쿼리의 예시는 콘텐츠 컬렉션
가이드를 참조하세요.
getEntries()
섹션 제목: getEntries()타입: (Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>
astro@2.5.0
getEntries()
는 동일한 컬렉션에서 여러 컬렉션 항목을 검색하는 함수입니다. 이는 참조된 항목의 배열을 반환하여 관련 data
및 body
속성에 액세스하는 데 유용합니다.
---import { getEntries } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// `data.relatedPosts`에 의해 참조되는 관련 게시물 가져오기const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);---
render()
섹션 제목: render()타입: () => Promise<RenderedEntry>
astro@5.0.0
렌더링을 위해 주어진 항목을 컴파일하는 함수입니다. 다음 속성들을 반환합니다:
<Content />
- Astro 파일에서 문서의 내용을 렌더링하는 데 사용되는 컴포넌트입니다.headings
- Markdown 및 MDX 가져오기에 대해 생성된 제목 목록, Astro의getHeadings()
유틸리티 미러링.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
타입
섹션 제목: astro:content 타입import type { CollectionEntry, CollectionKey, ContentCollectionKey, DataCollectionKey, SchemaContext, } from 'astro:content';
CollectionEntry
섹션 제목: CollectionEntrygetCollection()
, getEntry()
, getEntries()
를 포함한 쿼리 함수는 각각 CollectionEntry
타입의 항목을 반환합니다. 이 타입은 astro:content
에서 유틸리티로 사용할 수 있습니다.
import type { CollectionEntry } from 'astro:content';
CollectionEntry
는 제네릭 타입입니다. 이 타입을 쿼리하려는 컬렉션의 이름과 함께 사용하세요.
예를 들어, blog
컬렉션의 항목은 CollectionEntry<'blog'>
와 같은 타입을 가질 것입니다.
각 CollectionEntry
는 다음 값을 가지는 객체입니다.
타입 예시: 'author-1' | 'author-2' | ...
고유 ID입니다. Astro의 내장 glob()
로더의 모든 ID가 슬러그화된다는 점에 유의하세요.
collection
섹션 제목: collection타입 예시: 'blog' | 'authors' | ...
항목이 위치한 컬렉션의 이름입니다. 이는 스키마 및 쿼리 함수에서 컬렉션을 참조하는 데 사용되는 이름입니다.
data
섹션 제목: data타입: CollectionSchema<TCollectionName>
컬렉션 스키마에서 추론된 프런트매터 속성의 객체입니다 (defineCollection()
참조를 확인하세요). 스키마가 구성되지 않은 경우 기본값은 any
입니다.
body
섹션 제목: body타입: string
Markdown 또는 MDX 문서의 컴파일되지 않은 원시 본문을 포함하는 문자열입니다.
CollectionKey
섹션 제목: CollectionKey
Added in:
astro@3.1.0
src/content.config.*
파일에 정의된 모든 컬렉션 이름의 문자열 유니온 타입입니다. 이 타입은 모든 컬렉션 이름을 허용하는 일반 함수를 정의할 때 유용할 수 있습니다.
import { type CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) { return getCollection(collection);}
SchemaContext
섹션 제목: SchemaContextdefineCollection
이 schema
의 함수 모양을 위해 사용하는 context
객체입니다. 이 타입은 여러 컬렉션에 대해 재사용 가능한 스키마를 구축할 때 유용할 수 있습니다.
여기에는 다음 속성이 포함됩니다.
image
- 콘텐츠 컬렉션에서 로컬 이미지를 사용할 수 있게 해주는image()
스키마 도우미
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 }) }),});