`
diff --git a/src/content/docs/en/reference/content-loader-reference.mdx b/src/content/docs/en/reference/content-loader-reference.mdx
index 14a119663d97b..e8aa0e1a45287 100644
--- a/src/content/docs/en/reference/content-loader-reference.mdx
+++ b/src/content/docs/en/reference/content-loader-reference.mdx
@@ -5,19 +5,22 @@ sidebar:
i18nReady: true
---
import Since from '~/components/Since.astro';
+import ReadMore from '~/components/ReadMore.astro';
Astro's Content Loader API allows you to load your data from any source, local or remote, and interact with Astro's content layer to manage your [content collections](/en/guides/content-collections/).
## What is a loader?
-Astro loaders allow you to load data into [content collections](/en/guides/content-collections/), which can then be used in pages and components. The [built-in `glob()` and `file()` loaders](/en/guides/content-collections/#built-in-loaders) are used to load content from the file system, and you can create your own loaders to load content from other sources.
+Astro loaders allow you to load data into [content collections](/en/guides/content-collections/), which can then be used in pages and components. The [built-in `glob()` and `file()` loaders](#built-in-loaders) are used at built time to load content from the file system. You can also create your own [built-time loaders](/en/guides/content-collections/#custom-build-time-loaders) or [live loaders](/en/guides/content-collections/#creating-a-live-loader) to load content from other sources.
-Each collection needs [a loader defined in its schema](/en/guides/content-collections/#defining-the-collection-loader). You can define a loader inline in your project's `src/content.config.ts` file, share one loader between multiple collections, or even [publish your loader to NPM as a package](/en/reference/publish-to-npm/) to share with others and be included in our integrations library.
+Each collection needs to define a loader and an optional schema. For build-time collections, you can define a loader inline in your project's `src/content.config.ts` file or share an object loader between multiple collections. For live collections, you'll need to create your own live loader and import it in your `src/live.config.ts` file. In both cases, you can even [publish your loader to NPM as a package](/en/reference/publish-to-npm/) to share with others and be included in our integrations library.
## Built-in loaders
Astro provides two built-in loaders to help you fetch your collections. Both offer options to suit a wide range of use cases.
+Learn more about [using built-time loaders](/en/guides/content-collections/#build-time-content-collections) with guided explanations and example usage.
+
### `glob()` loader
@@ -30,19 +33,17 @@ The `glob()` loader creates entries from directories of files from anywhere on t
This loader accepts an object with the following properties: `pattern`, `base` (optional), and `generateId` (optional).
-```ts title="src/content.config.ts" {2,6,11,17-21}
+```ts title="src/content.config.ts" {2,6,10,15-19}
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
const pages = defineCollection({
/* Retrieve all Markdown files in your pages directory. */
loader: glob({ pattern: "**/*.md", base: "./src/data/pages" }),
- schema: /* ... */
});
const blog = defineCollection({
/* Retrieve all Markdown and MDX files in your blog directory. */
loader: glob({ pattern: "**/*.(md|mdx)", base: "./src/data/blog" }),
- schema: /* ... */
});
const authors = defineCollection({
/* Retrieve all JSON files in your authors directory while retaining
@@ -52,7 +53,6 @@ const authors = defineCollection({
base: "./src/data/authors",
generateId: ({ entry }) => entry.replace(/\.json$/, ''),
}),
- schema: /* ... */
});
```
@@ -103,21 +103,19 @@ The `file()` loader creates entries from a single file that contains an array of
This loader accepts a `fileName` property and an optional object as second argument:
-```ts title="src/content.config.ts" {2,6,11-13}
+```ts title="src/content.config.ts" {2,6,10-12}
import { defineCollection } from 'astro:content';
import { file } from 'astro/loaders';
const authors = defineCollection({
/* Retrieve all entries from a JSON file. */
loader: file("src/data/authors.json"),
- schema: /* ... */
});
const products = defineCollection({
/* Retrieve all entries from a CSV file using a custom parser. */
loader: file("src/data/products.csv", {
parser: (fileContent) => { /* your parser logic */ },
}),
- schema: /* ... */
});
```
@@ -159,6 +157,8 @@ An inline loader is an async function that returns an array or object containing
The function can be async and must return either an array of entries that each contain a unique `id` field, or an object where each key is a unique ID and each value is the entry. Whenever the loader is invoked, it will clear the store and reload all the entries.
```ts title="src/content.config.ts"
+import { defineCollection } from "astro:content";
+
const countries = defineCollection({
loader: async () => {
const response = await fetch("https://restcountries.com/v3.1/all");
@@ -170,18 +170,17 @@ const countries = defineCollection({
...country,
}));
},
- schema: /* ... */
});
```
### Object loaders
-A loader is an object with a `load()` method that is called at build time to fetch data and update the data store. It allows entries to be updated incrementally, or for the store to be cleared only when necessary. It can also define a schema for the entries, which can be used to validate the data and generate static types.
+A loader is an object with a [`load()` method](#load) that is called at build time to fetch data and update the data store. It allows [entries](#dataentry) to be updated incrementally, or for the store to be cleared only when necessary. It can also define a schema for the entries, which can be used to validate the data and generate static types.
The recommended pattern is to define a function that accepts configuration options and returns the loader object, in the same way that you would normally define an Astro integration or Vite plugin.
-```ts title=loader.ts
+```ts title="src/loader.ts"
import type { Loader, LoaderContext } from 'astro/loaders';
import { z } from 'astro:content';
import { loadFeedData } from "./feed.js";
@@ -210,21 +209,89 @@ export function myLoader(options: { url: string, apiKey: string }): Loader {
These configuration options can then be set when defining a collection:
```ts title="src/content.config.ts" {2,5-8}
-import { defineCollection, z } from 'astro:content';
-import myLoader from '../../loader.ts';
+import { defineCollection } from 'astro:content';
+import { myLoader } from './loader.ts';
-const blog = defineCollection({
+const blog = defineCollection({
loader: myLoader({
url: "https://api.example.com/posts",
apiKey: "my-secret",
- }),
- schema: /* ... */
-});
+ }),
+});
+```
+
+### Live loaders
+
+A live loader is an object with two methods: `loadCollection()` and `loadEntry()` that should handle errors gracefully and return either data or an `Error` object.
+
+```ts title="src/article-loader.ts"
+import type { LiveLoader } from 'astro/loaders';
+import { fetchFromCMS } from './cms-client.js';
+
+interface Article {
+ id: string;
+ title: string;
+ content: string;
+ author: string;
+}
+
+export function articleLoader(config: { apiKey: string }): LiveLoader {
+ return {
+ name: 'article-loader',
+ loadCollection: async ({ filter }) => {
+ try {
+ const articles = await fetchFromCMS({
+ apiKey: config.apiKey,
+ type: 'article',
+ filter,
+ });
+
+ return {
+ entries: articles.map((article) => ({
+ id: article.id,
+ data: article,
+ })),
+ };
+ } catch (error) {
+ return {
+ error: new Error(`Failed to load articles: ${error.message}`),
+ };
+ }
+ },
+ loadEntry: async ({ filter }) => {
+ try {
+ // filter will be { id: "some-id" } when called with a string
+ const article = await fetchFromCMS({
+ apiKey: config.apiKey,
+ type: 'article',
+ id: filter.id,
+ });
+
+ if (!article) {
+ return {
+ error: new Error('Article not found'),
+ };
+ }
+
+ return {
+ id: article.id,
+ data: article,
+ };
+ } catch (error) {
+ return {
+ error: new Error(`Failed to load article: ${error.message}`),
+ };
+ }
+ },
+ };
+}
```
+See [how to create a live loader](/en/guides/content-collections/#creating-a-live-loader) with example usage.
+
## Object loader API
-The API for [inline loaders](#inline-loaders) is very simple, and is shown above. This section shows the API for defining an object loader.
+The API for [inline loaders](#inline-loaders) is very simple, and is shown above. This section shows the API for defining an [object loader](#object-loaders).
### The `Loader` object
@@ -323,7 +390,7 @@ The full, resolved Astro configuration object with all defaults applied. See [th
Validates and parses the data according to the collection schema. Pass data to this function to validate and parse it before storing it in the data store.
-```ts title=loader.ts {14-17}
+```ts title=loader.ts {15-18}
import type { Loader } from "astro/loaders";
import { loadFeed } from "./feed.js";
@@ -337,8 +404,9 @@ export function feedLoader({ url }): Loader {
store.clear();
for (const item of feed.items) {
+ const id = item.guid;
const data = await parseData({
- id: item.guid,
+ id,
data: item,
});
store.set({
@@ -399,7 +467,7 @@ export function myLoader(settings): Loader {
Generates a non-cryptographic content digest of an object or string. This can be used to track if the data has changed by setting [the `digest` field](#digest) of an entry.
-```ts title=loader.ts {19,24}
+```ts title=loader.ts {20,25}
import type { Loader } from "astro/loaders";
import { loadFeed } from "./feed.js";
@@ -413,8 +481,9 @@ export function feedLoader({ url }): Loader {
store.clear();
for (const item of feed.items) {
+ const id = item.guid;
const data = await parseData({
- id: item.guid,
+ id,
data: item,
});
@@ -467,7 +536,10 @@ return {
If the loader has been triggered by an integration, this may optionally contain extra data set by that integration. It is only set when the loader is triggered by an integration. See the [`astro:server:setup`](/en/reference/integrations-reference/#refreshcontent-option) hook reference for more information.
-```ts title=loader.ts {5-8}
+```ts title=loader.ts {8-11}
+import type { Loader } from "astro/loaders";
+import { processWebhook } from "./lib/webhooks";
+
export function myLoader(options: { url: string }): Loader {
return {
name: "my-loader",
@@ -510,10 +582,11 @@ The returned object is a [`DataEntry`](#dataentry) object.
Used after data has been [validated and parsed](#parsedata) to add an entry to the store, returning `true` if the entry was set. This returns `false` when the [`digest`](#digest) property determines that an entry has not changed and should not be updated.
-```ts title=loader.ts {7-14}
+```ts title=loader.ts {8-15}
for (const item of feed.items) {
+ const id = item.guid;
const data = await parseData({
- id: item.guid,
+ id,
data: item,
});
const digest = generateDigest(data);
@@ -670,3 +743,67 @@ The format of the `RenderedContent` object is:
```
If the entry has Markdown content then you can use the [`renderMarkdown()`](#rendermarkdown) function to generate this object from the Markdown string.
+
+## Live loader API
+
+This section shows the API for defining a [live loader](#live-loaders).
+
+### The `LiveLoader` object
+
+A generic type to provide [type safety in your loader](/en/guides/content-collections/#type-safety-in-live-loaders). This describes an object and accepts four type parameters to describe, in this order: your data structure, your filters when querying a collection, your filters when querying a single entry, and errors.
+
+This object contains the following properties:
+
+#### `name`
+
+
+
+**Type:** `string`
+
+
+
+A unique name for the loader, used in logs.
+
+#### `loadCollection()`
+
+
+
+**Type:** `(context: LoadCollectionContext) => Promise | { error: TError; }>`
+
+
+Defines a method to load a collection of entries. This function receives a [context object](#loadcollectioncontext) containing an optional `filter` property and must return the data associated with this collection or the errors.
+
+#### `loadEntry()`
+
+
+
+**Type:** `(context: LoadEntryContext) => Promise | undefined | { error: TError; }>`
+
+
+Defines a method to load a single entry. This function receives a [context object](#loadentrycontext) containing a `filter` property and returns either the data associated with the requested entry, `undefined` when the entry cannot be found, or the errors.
+
+### `LoadCollectionContext`
+
+This object is passed to the [`loadCollection()` method](#loadcollection) of the loader and contains the following properties:
+
+#### `filter`
+
+
+
+**Type:** `Record`
+
+
+An object describing the filters supported by your loader.
+
+### `LoadEntryContext`
+
+This object is passed to the [`loadEntry()` method](#loadentry) of the loader and contains the following properties:
+
+#### `filter`
+
+
+
+**Type:** `Record`
+
+
+An object describing the filters supported by your loader.
diff --git a/src/content/docs/en/reference/errors/content-collection-missing-loader.mdx b/src/content/docs/en/reference/errors/content-collection-missing-loader.mdx
index 224406aa602c6..13652a54399f6 100644
--- a/src/content/docs/en/reference/errors/content-collection-missing-loader.mdx
+++ b/src/content/docs/en/reference/errors/content-collection-missing-loader.mdx
@@ -21,4 +21,4 @@ import DontEditWarning from '~/components/DontEditWarning.astro'
A content collection is missing a loader definition. Make sure that each collection in your content config file has a loader.
**See Also:**
-- [Content collections configuration](/en/guides/content-collections/#defining-the-collection-loader)
+- [Content collections configuration](/en/guides/content-collections/)
diff --git a/src/content/docs/en/reference/errors/file-glob-not-supported.mdx b/src/content/docs/en/reference/errors/file-glob-not-supported.mdx
index 9918fdd56ccb5..be9f4ce3a5767 100644
--- a/src/content/docs/en/reference/errors/file-glob-not-supported.mdx
+++ b/src/content/docs/en/reference/errors/file-glob-not-supported.mdx
@@ -19,6 +19,6 @@ import DontEditWarning from '~/components/DontEditWarning.astro'
The `file` loader must be passed a single local file. Glob patterns are not supported. Use the built-in `glob` loader to create entries from patterns of multiple local files.
**See Also:**
-- [Astro's built-in loaders](/en/guides/content-collections/#built-in-loaders)
+- [Astro's built-in `file()` loader](/en/guides/content-collections/#the-file-loader)
diff --git a/src/content/docs/en/reference/errors/legacy-content-config-error.mdx b/src/content/docs/en/reference/errors/legacy-content-config-error.mdx
index 8dcd318ea0da5..4da8ce6546963 100644
--- a/src/content/docs/en/reference/errors/legacy-content-config-error.mdx
+++ b/src/content/docs/en/reference/errors/legacy-content-config-error.mdx
@@ -23,4 +23,4 @@ A legacy content config file was found. Move the file to `src/content.config.ts`
See the [Astro 6 migration guide](/en/guides/upgrade-to/v6/#removed-legacy-content-collections) for more information.
**See Also:**
-- [Content collections configuration](/en/guides/content-collections/#the-collection-config-file)
+- [Content collections configuration](/en/guides/content-collections/#build-time-content-collections)
diff --git a/src/content/docs/en/reference/modules/astro-content.mdx b/src/content/docs/en/reference/modules/astro-content.mdx
index cc72bd2d2a523..bf4a2510da1db 100644
--- a/src/content/docs/en/reference/modules/astro-content.mdx
+++ b/src/content/docs/en/reference/modules/astro-content.mdx
@@ -12,7 +12,13 @@ import ReadMore from '~/components/ReadMore.astro';
-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](/en/guides/content-collections/).
+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.
+
+
+
+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](/en/guides/content-collections/).
## Imports from `astro:content`
@@ -20,13 +26,17 @@ Content collections offer APIs to configure and query your Markdown or MDX docum
import {
z,
defineCollection,
+ defineLiveCollection,
getCollection,
+ getLiveCollection,
getEntry,
+ getLiveEntry,
getEntries,
reference,
render
} from 'astro:content';
```
+
### `defineCollection()`
@@ -35,7 +45,7 @@ import {
-`defineCollection()` is a utility to configure a collection in a `src/content.config.*` file.
+A utility to configure a collection in a `src/content.config.*` file.
```ts title="src/content.config.ts"
import { z, defineCollection } from 'astro:content';
@@ -64,9 +74,9 @@ This function accepts the following properties:
-A `loader` is either an object or a function that allows you to load data from any source, local or remote, into content collections.
+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`](#loader-1) property.)
-[See the `Content Collection` guide](/en/guides/content-collections/#defining-the-collection-loader) for example usage.
+Learn about [build-time collection loaders](/en/guides/content-collections/#build-time-collection-loaders) with guided explanations and example usage.
#### `schema`
@@ -76,24 +86,77 @@ A `loader` is either an object or a function that allows you to load data from a
-`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](https://github.com/colinhacks/zod).
+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](https://github.com/colinhacks/zod). (For live collections, see the [live `schema`](#schema-1) property.)
+
+Learn about [defining a collection schema](/en/guides/content-collections/#defining-the-collection-schema) using Zod with guided explanations, example usage, and common datatypes.
+
+### `defineLiveCollection()`
+
+
+
+**Type:** `(config: LiveCollectionConfig) => LiveCollectionConfig`
+
+
+
+A utility to configure a live collection in a `src/live.config.*` file.
+
+```ts title="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',
+ }),
+});
+
+// Expose your defined collection to Astro
+// with the `collections` export
+export const collections = { products };
+```
+
+This function accepts the following properties:
+
+#### `loader`
+
+
+
+**Type:** `LiveLoader`
+
+
+
+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`](#loader) property.)
+
+Learn how to [create a live loader](/en/guides/content-collections/#creating-a-live-loader) with guided explanations and example usage.
-[See the `Content Collection` guide](/en/guides/content-collections/#defining-the-collection-schema) for example usage.
+#### `schema`
+
+
+
+**Type:** ZodType
+
+
+
+An optional Zod object to configure the type and shape of your data for a live collection. Each value must use [a Zod validator](https://github.com/colinhacks/zod). (For build-time collections, see the [build-time `schema`](#schema) property.)
+
+When you define a schema, it will take precedence over the [live loader’s types](/en/reference/content-loader-reference/#live-loader-api) when you query the collection.
+
+Learn about [using Zod schemas with live collections](/en/guides/content-collections/#using-zod-schemas-with-live-collections) through guided explanations and usage examples.
### `reference()`
-**Type:** `(collection: string) => ZodEffects`
+**Type:** (collection: CollectionKey) => ZodEffects\
-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 transforms the reference into an object containing the collection name and the reference id.
-
+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:
-```ts
+```ts title="src/content.config.ts"
import { defineCollection, reference, z } from 'astro:content';
import { glob, file } from 'astro/loaders';
@@ -114,6 +177,7 @@ const authors = defineCollection({
export const collections = { blog, authors };
```
+
Validation of referenced entries happens at runtime when using `getEntry()` or `getEntries()`:
```astro title="src/pages/[posts].astro"
@@ -121,25 +185,25 @@ Validation of referenced entries happens at runtime when using `getEntry()` or `
const relatedPosts = await getEntries(blogPost.data.relatedPosts);
```
-[See the `Content Collection` guide](/en/guides/content-collections/#defining-collection-references) for example usage.
+Learn how to [define and use collection references](/en/guides/content-collections/#defining-collection-references) with guided explanations and usage examples.
### `getCollection()`
-**Type:** `(collection: string, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]`
+**Type:** (collection: CollectionKey, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]
-`getCollection()` is a function that retrieves a list of content collection entries by collection name.
+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.
-```astro
+```astro title="src/pages/blog/index.astro"
---
import { getCollection } from 'astro:content';
-// Get all `src/content/blog/` entries
+// Get all `src/data/blog/` entries
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatter
@@ -149,21 +213,47 @@ const draftBlogPosts = await getCollection('blog', ({ data }) => {
---
```
-[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage.
+Learn how to [query build time collections](/en/guides/content-collections/#querying-build-time-collections) with guided explanations and example usage.
+
+### `getLiveCollection()`
+
+
+
+**Type:** `(collection: string, filter?: LiveLoaderCollectionFilterType) => Promise`
+
+
+
+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.
+
+```astro title="src/pages/shop/index.astro"
+---
+import { getLiveCollection } from 'astro:content';
+
+// Get all `products` entries from your API
+const allProducts = await getLiveCollection('products');
+
+// Only return `products` that should be featured
+const featuredProducts = await getLiveCollection('products', { featured: true });
+---
+```
+
+Learn how to [access live collections data](/en/guides/content-collections/#accessing-live-data) with guided explanations and example usage.
### `getEntry()`
**Types:**
-* `(collection: string, id: string) => Promise | undefined>`
-* `({ collection: string, id: string }) => Promise | undefined>`
+* (collection: CollectionKey, id: string) => Promise\<CollectionEntry | undefined\>
+* (\{ collection: CollectionKey, id: string \}) => Promise\<CollectionEntry | undefined\>
-`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:
+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:
-```astro
+```astro title="src/pages/index.astro"
---
import { getEntry } from 'astro:content';
@@ -178,19 +268,43 @@ const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---
```
-See the `Content Collections` guide for examples of [querying collection entries](/en/guides/content-collections/#querying-collections).
+Learn more about [querying build time collections](/en/guides/content-collections/#querying-build-time-collections) with guided explanations and example usage.
+
+### `getLiveEntry()`
+
+
+
+**Type:** `(collection: string, filter: string | LiveLoaderEntryFilterType) => Promise`
+
+
+
+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.
+
+```astro title="src/pages/blog/[id].astro"
+---
+import { getLiveEntry } from 'astro:content';
+
+const liveCollectionsPost = await getLiveEntry('blog', Astro.params.id);
+const mattDraft = await getLiveEntry('blog', {
+ status: 'draft',
+ author: 'matt',
+});
+---
+```
+
+Learn how to [access live collections data](/en/guides/content-collections/#accessing-live-data) with guided explanations and example usage.
### `getEntries()`
-**Type:** `(Array<{ collection: string, id: string }>) => Array>`
+**Type:** (\{ collection: CollectionKey, id: string \}[]) => CollectionEntry[]
-`getEntries()` is a function that retrieves multiple collection entries from the same collection. This is useful for [returning an array of referenced entries](/en/guides/content-collections/#defining-collection-references) to access their associated `data` and `body` properties.
+A function that retrieves multiple collection entries from the same collection. This is useful for [returning an array of referenced entries](/en/guides/content-collections/#defining-collection-references) to access their associated `data` and `body` properties.
-```astro
+```astro title="src/pages/blog/enterprise/index.astro"
---
import { getEntries, getEntry } from 'astro:content';
@@ -205,7 +319,7 @@ const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts
-**Type:** `(entry: CollectionEntry) => Promise`
+**Type:** (entry: CollectionEntry) => Promise\
@@ -215,7 +329,7 @@ A function to compile a given entry for rendering. This returns the following pr
- `headings` - A generated list of headings, [mirroring Astro's `getHeadings()` utility](/en/guides/markdown-content/#available-properties) on Markdown and MDX imports.
- `remarkPluginFrontmatter ` - The modified frontmatter object after any [remark or rehype plugins have been applied](/en/guides/markdown-content/#modifying-frontmatter-programmatically). Set to type `any`.
-```astro
+```astro title="src/pages/blog/entry-1.astro"
---
import { getEntry, render } from 'astro:content';
const entry = await getEntry('blog', 'entry-1');
@@ -228,7 +342,7 @@ const { Content, headings, remarkPluginFrontmatter } = await render(entry);
---
```
-[See the `Content Collection` guide](/en/guides/content-collections/#rendering-body-content) for example usage.
+Learn how to [render the body content of entries](/en/guides/content-collections/#rendering-body-content) with guided explanations and example usage.
## `astro:content` types
@@ -236,8 +350,6 @@ const { Content, headings, remarkPluginFrontmatter } = await render(entry);
import type {
CollectionEntry,
CollectionKey,
- ContentCollectionKey,
- DataCollectionKey,
SchemaContext,
} from 'astro:content';
```
@@ -250,45 +362,79 @@ Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#g
import type { CollectionEntry } from 'astro:content';
```
-`CollectionEntry` is a generic type. Use it with the name of the collection you're querying.
+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:
#### `id`
+
+
**Type:** `string`
+
A unique ID. Note that all IDs from Astro's built-in `glob()` loader are slugified.
#### `collection`
-**Example Type:** `'blog' | 'authors' | ...`
+
+
+**Type:** [`CollectionKey`](#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.
+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.
#### `data`
+
+
**Type:** `CollectionSchema`
+
An object of frontmatter properties inferred from your collection schema ([see `defineCollection()` reference](#definecollection)). Defaults to `any` if no schema is configured.
#### `body`
+
+
**Type:** `string`
+
A string containing the raw, uncompiled body of the Markdown or MDX document.
+#### `rendered`
+
+
+
+**Type:** `RenderedContent | undefined`
+
+
+The rendered content of an entry as [stored by your loader](/en/reference/content-loader-reference/#rendered). For example, this can be the rendered content of a Markdown entry, or HTML from a CMS.
+
+#### `filePath`
+
+
+
+**Type:** `string | undefined`
+
+
+The path to an entry relative to your project directory. This value is only available for local entries.
+
### `CollectionKey`
-
+
+
+**Example Type:** `'blog' | 'authors' | ...`
+
+
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()`.
-```ts
+```ts title="src/utils/collections.ts"
import { type CollectionKey, getCollection } from 'astro:content';
-async function queryCollection(collection: CollectionKey) {
+export async function queryCollection(collection: CollectionKey) {
return getCollection(collection, ({ data }) => {
return data.draft !== true;
});
@@ -303,8 +449,9 @@ This includes the following property:
- `image` - The `image()` schema helper that allows you [to use local images in Content Collections](/en/guides/images/#images-in-content-collections)
-```ts
+```ts title="src/content.config.ts" "SchemaContext" {4-8,12,15}
import { defineCollection, z, type SchemaContext } from "astro:content";
+import { glob } from 'astro/loaders';
export const imageSchema = ({ image }: SchemaContext) =>
z.object({
@@ -313,7 +460,7 @@ export const imageSchema = ({ image }: SchemaContext) =>
});
const blog = defineCollection({
- loader: /* ... */,
+ loader: glob({ pattern: '**/*.md', base: './src/data/blog' }),
schema: ({ image }) => z.object({
title: z.string(),
permalink: z.string().optional(),
diff --git a/src/content/docs/en/tutorial/6-islands/4.mdx b/src/content/docs/en/tutorial/6-islands/4.mdx
index 06ad6a55abe89..066162404180c 100644
--- a/src/content/docs/en/tutorial/6-islands/4.mdx
+++ b/src/content/docs/en/tutorial/6-islands/4.mdx
@@ -147,7 +147,7 @@ Upgrade to the latest version of Astro, and upgrade all integrations to their la
1. Create a page file called `src/pages/posts/[...slug].astro`. Your Markdown and MDX files no longer automatically become pages using Astro's file-based routing when they are inside a collection, so you must create a page responsible for generating each individual blog post.
-2. Add the following code to [query your collection](/en/guides/content-collections/#querying-collections) to make each blog post's slug and page content available to each page it will generate:
+2. Add the following code to [query your collection](/en/guides/content-collections/#querying-build-time-collections) to make each blog post's slug and page content available to each page it will generate:
```astro title="src/pages/posts/[...slug].astro"
---
diff --git a/src/content/docs/es/guides/media/cloudinary.mdx b/src/content/docs/es/guides/media/cloudinary.mdx
index cfdc59827c996..06f370ff11486 100644
--- a/src/content/docs/es/guides/media/cloudinary.mdx
+++ b/src/content/docs/es/guides/media/cloudinary.mdx
@@ -134,7 +134,7 @@ export const collections = {
}
```
-Luego puedes usar las [funciones de consulta `getCollection()` o `getEntry()`](/es/guides/content-collections/#querying-collections) para seleccionar una o varias imágenes o vídeos de tu colección.
+Luego puedes usar las [funciones de consulta `getCollection()` o `getEntry()`](/es/guides/content-collections/#querying-build-time-collections) para seleccionar una o varias imágenes o vídeos de tu colección.
Consulta la [documentación de `cldAssetsLoader` de Cloudinary](https://astro.cloudinary.dev/cldassetsloader/basic-usage) para más información.
diff --git a/src/content/docs/es/tutorial/6-islands/4.mdx b/src/content/docs/es/tutorial/6-islands/4.mdx
index 332658a62fa65..5a29231adb35a 100644
--- a/src/content/docs/es/tutorial/6-islands/4.mdx
+++ b/src/content/docs/es/tutorial/6-islands/4.mdx
@@ -145,7 +145,7 @@ Actualiza a la última versión de Astro y actualiza todas las integraciones a s
1. Crea un archivo de página llamado `src/pages/posts/[...slug].astro`. Tus archivos Markdown y MDX ya no se convierten automáticamente en páginas usando el enrutamiento basado en archivos de Astro cuando están dentro de una colección, por lo que debes crear una página responsable de generar cada publicación de blog individual.
-2. Agrega el siguiente código para [consultar tu colección](/es/guides/content-collections/#querying-collections) para que el slug de cada publicación de blog y el contenido de la página estén disponibles para cada página que generará:
+2. Agrega el siguiente código para [consultar tu colección](/es/guides/content-collections/#querying-build-time-collections) para que el slug de cada publicación de blog y el contenido de la página estén disponibles para cada página que generará:
```astro title="src/pages/posts/[...slug].astro"
---
diff --git a/src/content/docs/it/tutorial/6-islands/4.mdx b/src/content/docs/it/tutorial/6-islands/4.mdx
index 167a08a9c3038..0e5ca0a650933 100644
--- a/src/content/docs/it/tutorial/6-islands/4.mdx
+++ b/src/content/docs/it/tutorial/6-islands/4.mdx
@@ -144,7 +144,7 @@ Aggiorna all'ultima versione di Astro e aggiorna tutte le integrazioni alle loro
1. Crea un file pagina chiamato `src/pages/posts/[...slug].astro`. I tuoi file Markdown e MDX non diventano più automaticamente pagine usando il routing basato su file di Astro quando si trovano all'interno di una raccolta, quindi devi creare una pagina responsabile della generazione di ogni singolo articolo del blog.
-2. Aggiungi il seguente codice per [interrogare la tua raccolta](/it/guides/content-collections/#querying-collections) per rendere disponibili lo slug e il contenuto della pagina di ogni articolo del blog a ogni pagina che genererà:
+2. Aggiungi il seguente codice per [interrogare la tua raccolta](/it/guides/content-collections/#querying-build-time-collections) per rendere disponibili lo slug e il contenuto della pagina di ogni articolo del blog a ogni pagina che genererà:
```astro title="src/pages/posts/[...slug].astro"
---
diff --git a/src/content/docs/ja/guides/integrations-guide/markdoc.mdx b/src/content/docs/ja/guides/integrations-guide/markdoc.mdx
index edd950cf75a99..8272fb0f42381 100644
--- a/src/content/docs/ja/guides/integrations-guide/markdoc.mdx
+++ b/src/content/docs/ja/guides/integrations-guide/markdoc.mdx
@@ -113,7 +113,7 @@ Markdocファイルは、コンテンツコレクション内でのみ使用で
- quick-start.mdoc
-次に、[コンテンツコレクションAPI](/ja/guides/content-collections/#querying-collections)を使用してコレクションをクエリします。
+次に、[コンテンツコレクションAPI](/ja/guides/content-collections/#querying-build-time-collections)を使用してコレクションをクエリします。
```astro title="src/pages/why-markdoc.astro"
---
diff --git a/src/content/docs/ja/guides/migrate-to-astro/from-create-react-app.mdx b/src/content/docs/ja/guides/migrate-to-astro/from-create-react-app.mdx
index 0f109b9fb6c85..940d7cc185bde 100644
--- a/src/content/docs/ja/guides/migrate-to-astro/from-create-react-app.mdx
+++ b/src/content/docs/ja/guides/migrate-to-astro/from-create-react-app.mdx
@@ -329,7 +329,7 @@ const randomUser = data.results[0];
```
- `import.meta.glob()`によるローカルファイル取得
-- Collections APIのクエリ: [/ja/guides/content-collections/#コレクションのクエリ](/ja/guides/content-collections/#querying-collections)
+- Collections APIのクエリ: [/ja/guides/content-collections/#コレクションのクエリ](/ja/guides/content-collections/#querying-build-time-collections)
- リモートデータのフェッチ: [/ja/guides/data-fetching/](/ja/guides/data-fetching/)
### CRAのスタイリングをAstroへ
diff --git a/src/content/docs/pt-br/tutorial/6-islands/4.mdx b/src/content/docs/pt-br/tutorial/6-islands/4.mdx
index 4dc53475bb4c1..79ea4987e4ba6 100644
--- a/src/content/docs/pt-br/tutorial/6-islands/4.mdx
+++ b/src/content/docs/pt-br/tutorial/6-islands/4.mdx
@@ -144,7 +144,7 @@ Atualize para a última versão do Astro, e atualize todas as integrações para
1. Crie um arquivo de página chamado `src/pages/posts/[...slug].astro`. Seus arquivos Markdown e MDX não mais se tornarão páginas automaticamente usando o roteamento baseado em arquivos Astro quando estão dentro de uma coleção, então você precisa criar a página responsável para gerar cada postagem de blog individual.
-2. Adicione o seguinte código para [consultar sua coleção](/pt-br/guides/content-collections/#querying-collections) para fazer cada slug e conteúdo de postagem de blog disponível para cada página que será gerada:
+2. Adicione o seguinte código para [consultar sua coleção](/pt-br/guides/content-collections/#querying-build-time-collections) para fazer cada slug e conteúdo de postagem de blog disponível para cada página que será gerada:
```astro title="src/pages/posts/[...slug].astro"
---
diff --git a/src/content/docs/ru/reference/errors/mixed-content-data-collection-error.mdx b/src/content/docs/ru/reference/errors/mixed-content-data-collection-error.mdx
index a5986f5139e96..652b78ca9cc40 100644
--- a/src/content/docs/ru/reference/errors/mixed-content-data-collection-error.mdx
+++ b/src/content/docs/ru/reference/errors/mixed-content-data-collection-error.mdx
@@ -10,6 +10,3 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/
Коллекция контента не может содержать смешанные записи контента и данных. Вы должны хранить записи в отдельных коллекциях по типу.
-**Смотрите также:**
-
-- [Определение коллекций контента](/ru/guides/content-collections/#defining-collections)
\ No newline at end of file
diff --git a/src/content/docs/ru/tutorial/6-islands/4.mdx b/src/content/docs/ru/tutorial/6-islands/4.mdx
index 635c8eb29684d..bec07253313a2 100644
--- a/src/content/docs/ru/tutorial/6-islands/4.mdx
+++ b/src/content/docs/ru/tutorial/6-islands/4.mdx
@@ -144,7 +144,7 @@ import { Steps } from '@astrojs/starlight/components';
1. Создайте файл страницы с именем `src/pages/posts/[...slug].astro`. Ваши файлы Markdown и MDX больше не становятся автоматически страницами при использовании маршрутизации на основе файлов в Astro, когда они находятся внутри коллекции, поэтому вы должны создать страницу, отвечающую за генерацию каждого отдельного поста блога.
-2. Добавьте следующий код, чтобы [запросить вашу коллекцию](/ru/guides/content-collections/#querying-collections) и сделать slug и содержимое всех страниц доступными для генерации соответствующих постов.
+2. Добавьте следующий код, чтобы [запросить вашу коллекцию](/ru/guides/content-collections/#querying-build-time-collections) и сделать slug и содержимое всех страниц доступными для генерации соответствующих постов.
```astro title="src/pages/posts/[...slug].astro"
---