Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

content-collections: Add example to render list of contents #8364

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/content/docs/en/guides/content-collections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,34 @@ const { Content, headings } = await entry.render();
```


### Render a list of contents

Sometimes, you don't just want to [render one Content to HTML](#rendering-content-to-html) but a list of contents, like on the index page of a blog.

```astro
---
// src/pages/render-list-example.astro
import { getCollection } from 'astro:content';
const blogpostsCollection = await getCollection('blog')
const blogposts = []
for (const blogpost of blogpostsCollection) {
const { Content } = await blogpost.render()
blogposts.push({
slug: blogpost.slug,
title: blogpost.data.title,
Content: Content,
})
}
---
<h1>Blogposts ({blogposts.length})</h1>
{
blogposts.map(({ slug, title, Content }) => (
<article><Content /></article>
))
}
```


## Generating Routes from Content

Content collections are stored outside of the `src/pages/` directory. This means that no routes are generated for your collection items by default. You will need to manually create a new [dynamic route](/en/guides/routing/#dynamic-routes) to generate HTML pages from your collection entries. Your dynamic route will map the incoming request param (ex: `Astro.params.slug` in `src/pages/blog/[...slug].astro`) to fetch the correct entry inside a collection.
Expand Down
Loading