Data, content, and assets
Query and render a collection
Load entries, filter drafts, sort dates, and pass one consistent content shape into the page.
8 minute lesson
~~~
Query build-time content with getCollection():
---
import { getCollection } from "astro:content"
const notes = await getCollection("notes", ({ data }) => !data.draft)
notes.sort(
(a, b) => b.data.publishedAt.valueOf() - a.data.publishedAt.valueOf()
)
---
<ul>
{notes.map(note => (
<li><a href={`/notes/${note.id}/`}>{note.data.title}</a></li>
))}
</ul>
Do not rely on the loader’s entry order; sort explicitly where the listing policy belongs. Filter drafts before creating links or routes so unpublished URLs are not accidentally generated.
For a detail route, select the entry in getStaticPaths() and render its body:
---
import { getCollection, render } from "astro:content"
export async function getStaticPaths() {
const notes = await getCollection("notes", ({ data }) => !data.draft)
return notes.map(note => ({ params: { id: note.id }, props: { note } }))
}
const { note } = Astro.props
const { Content } = await render(note)
---
<h1>{note.data.title}</h1>
<Content />
Keep selection and sorting near the route. Presentational components should receive a small, consistent shape instead of knowing how the entire collection is stored.
Lesson completed