#How to get the current page's collection?

2 messages · Page 1 of 1 (latest)

small hillBOT
#

Hi @main dagger. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, you can use the getCollection() function from the astro:content module to query a collection. This function is used in the frontmatter of an Astro component and it returns a Promise that resolves to an array of collection items. Here's an example of how you can use it:

---
import { getCollection } from 'astro:content';
const posts = await getCollection('posts');
---

In this example, getCollection('posts') is used to get all the items in the 'posts' collection. Each item in the collection is an object that contains the post's frontmatter data, its content, and other metadata.

If you want to get a single entry from a collection, you can use the getEntry() or getEntryBySlug() function. Here's an example:

---
import { getEntry } from 'astro:content';
const post = await getEntry('posts', 'my-first-post');
const { Content } = await post.render();
---
<main>
  <h1>{post.data.title}</h1>
  <Content />
</main>

In this example, getEntry('posts', 'my-first-post') is used to get a single post from the 'posts' collection. The post.render() function is then used to render the post's content to HTML.

For more information on querying collections, you can refer to the Astro Content Collections documentation (https://docs.astro.build/en/guides/content-collections/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: