#How to render all content in a collection on one page?

4 messages · Page 1 of 1 (latest)

devout verge
#

I have a content collection and I want to create a series of divs all one one page, each of which contains the rendered content of an item from the collection. How can I do that?

cerulean phoenixBOT
#

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

#

To render all content from a collection on one page in Astro, you can follow these steps:

  1. First, query your collection using the getCollection() function from astro:content.
  2. Then, map over the collection items to create a series of divs, each containing the rendered content of an item.

Here's an example of how you can achieve this:

---
import { getCollection, render } from 'astro:content';

// Get all entries from your collection
const allItems = await getCollection('yourCollectionName');

// Render each item's content
const renderedItems = await Promise.all(
  allItems.map(async (item) => {
    const { Content } = await render(item);
    return { ...item, Content };
  })
);
---

<html>
  <head>
    <title>All Collection Items</title>
  </head>
  <body>
    {renderedItems.map((item) => (
      <div>
        <h2>{item.data.title}</h2>
        <item.Content />
      </div>
    ))}
  </body>
</html>

In this example:

  1. We use getCollection() to fetch all items from your collection as described in the Astro documentation (https://docs.astro.build/en/guides/content-collections/#querying-collections).
  2. We then use Promise.all() with render() to render the content of each item as shown in the Astro documentation (https://docs.astro.build/en/guides/content-collections/#rendering-body-content).
  3. Finally, we use a map function in the template to create a div for each item, displaying its title and rendered content.

Remember to replace 'yourCollectionName' with the actual name of your collection.

This approach will render all items from your collection on a single page, each within its own div. The content of each item will be fully rendered, including any Markdown or MDX content.