Content Collections API Reference
यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।
जोड़ा गया:
astro@2.0.0
Build-time content collections offer APIs to configure, query, and render your local Markdown, MDX, Markdoc, YAML, TOML, or JSON files, as well as remote content.
जोड़ा गया:
astro@6.0.0
बीटा
Live content collections offer APIs to configure, query, and render fresh, up-to-the-moment live data from remote sources.
For features and usage examples, see our content collections guide.
Imports from astro:content
Section titled “Imports from astro:content”import { z, defineCollection, defineLiveCollection, getCollection, getLiveCollection, getEntry, getLiveEntry, getEntries, reference, render } from 'astro:content';defineCollection()
Section titled “defineCollection()”Type: (input: CollectionConfig) => CollectionConfig
astro@2.0.0
A utility to configure a collection in a src/content.config.* file.
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` exportexport const collections = { blog };This function accepts the following properties:
loader
Section titled “loader”Type: () => Promise<Array<{ id: string, [key: string]: any }> | Record<string, Record<string, any>>> | Loader
astro@5.0.0
Either an object or a function that allows you to load data from any source, local or remote, into a build-time content collection. (For live collections, see the live loader property.)
schema
Section titled “schema”Type: ZodType | (context: SchemaContext) => ZodType
astro@2.0.0
An optional Zod object or function that returns a Zod object to configure the type and shape of document frontmatter for a collection. Each value must use a Zod validator. (For live collections, see the live schema property.)
defineLiveCollection()
Section titled “defineLiveCollection()”Type: (config: LiveCollectionConfig) => LiveCollectionConfig
astro@6.0.0
बीटा
A utility to configure a live collection in a src/live.config.* file.
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', }),});
// Expose your defined collection to Astro// with the `collections` exportexport const collections = { products };This function accepts the following properties:
loader
Section titled “loader”Type: LiveLoader
astro@6.0.0
बीटा
An object that allows you to load data at runtime from a remote source into a live content collection. (For build-time collections, see the build-time loader property.)
schema
Section titled “schema”Type: ZodType
astro@6.0.0
बीटा
An optional Zod object to configure the type and shape of your data for a live collection. Each value must use a Zod validator. (For build-time collections, see the build-time schema property.)
When you define a schema, it will take precedence over the live loader’s types when you query the collection.
reference()
Section titled “reference()”Type: (collection: CollectionKey) => ZodEffects<ZodString, { collection: CollectionKey, id: string }>
astro@2.5.0
A function used in the content config to define a relationship, or “reference”, from one collection to another. This accepts a collection name and transforms the reference into an object containing the collection name and the reference id.
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 };Validation of referenced entries happens at runtime when using getEntry() or getEntries():
// if a referenced entry is invalid, this will return undefined.const relatedPosts = await getEntries(blogPost.data.relatedPosts);getCollection()
Section titled “getCollection()”Type: (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]
astro@2.0.0
A function that retrieves a list of content collection entries by collection name.
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/data/blog/` entriesconst allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatterconst draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});---getLiveCollection()
Section titled “getLiveCollection()”Type: (collection: string, filter?: LiveLoaderCollectionFilterType) => Promise<LiveDataCollectionResult>
astro@6.0.0
बीटा
A function that retrieves a list of live content collection entries by collection name.
It returns all items in the collection by default, and accepts an optional filter object whose shape is defined by the collection’s loader. This allows you to query for only some items in a collection or retrieve data in a different form, depending on your API’s capabilities.
---import { getLiveCollection } from 'astro:content';
// Get all `products` entries from your APIconst allProducts = await getLiveCollection('products');
// Only return `products` that should be featuredconst featuredProducts = await getLiveCollection('products', { featured: true });---getEntry()
Section titled “getEntry()”Types:
-
(collection: CollectionKey, id: string) => Promise<CollectionEntry | undefined> -
({ collection: CollectionKey, id: string }) => Promise<CollectionEntry | undefined>
astro@2.5.0
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);---getLiveEntry()
Section titled “getLiveEntry()”Type: (collection: string, filter: string | LiveLoaderEntryFilterType) => Promise<LiveDataEntryResult>
astro@6.0.0
बीटा
A function that retrieves a single live collection entry by collection name and an optional filter, either as an id string or as a type-safe object.
---import { getLiveEntry } from 'astro:content';
const liveCollectionsPost = await getLiveEntry('blog', Astro.params.id);const mattDraft = await getLiveEntry('blog', { status: 'draft', author: 'matt',});---getEntries()
Section titled “getEntries()”Type: ({ collection: CollectionKey, id: string }[]) => CollectionEntry[]
astro@2.5.0
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, getEntry } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// Get related posts referenced by `data.relatedPosts`const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);---render()
Section titled “render()”Type: (entry: CollectionEntry) => Promise<RenderResult>
astro@5.0.0
A function to compile a given entry for rendering. This returns the following properties:
<Content />- A component used to render the document’s contents in an Astro file.headings- A generated list of headings, mirroring Astro’sgetHeadings()utility on Markdown and MDX imports.remarkPluginFrontmatter- The modified frontmatter object after any remark or rehype plugins have been applied. Set to typeany.
---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);---astro:content types
Section titled “astro:content types”import type { CollectionEntry, CollectionKey, SchemaContext, } from 'astro:content';CollectionEntry
Section titled “CollectionEntry”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';A generic type to use with the name of the collection you’re querying to represent a single entry in that collection.
For example, an entry in your blog collection would have the type CollectionEntry<'blog'>.
Each CollectionEntry is an object with the following values:
Type: string
A unique ID. Note that all IDs from Astro’s built-in glob() loader are slugified.
collection
Section titled “collection”Type: CollectionKey
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.
Type: CollectionSchema<TCollectionName>
An object of frontmatter properties inferred from your collection schema (see defineCollection() reference). Defaults to any if no schema is configured.
Type: string
A string containing the raw, uncompiled body of the Markdown or MDX document.
rendered
Section titled “rendered”Type: RenderedContent | undefined
The rendered content of an entry as stored by your loader. For example, this can be the rendered content of a Markdown entry, or HTML from a CMS.
filePath
Section titled “filePath”Type: string | undefined
The path to an entry relative to your project directory. This value is only available for local entries.
CollectionKey
Section titled “CollectionKey”Example Type: 'blog' | 'authors' | ...
astro@3.1.0
A string union of all collection names defined in your src/content.config.* file. This type can be useful when defining a generic function wrapping the built-in 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”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:
image- Theimage()schema helper that allows you to use local images in Content Collections
import { defineCollection, z, type SchemaContext } from "astro:content";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 }) }),});