Introduction
Rendering collection content helps you show lists of data from your database on your website in a clear and organized way.
import { getCollection } from 'astro:content'; const collection = await getCollection('collectionName'); --- <ul> {collection.map(item => ( <li>{item.data.title}</li> ))} </ul>
import { getCollection } from 'astro:content'; and await getCollection('collectionName') to get all items from a collection..map() to loop through each item and render it.import { getCollection } from 'astro:content'; const posts = await getCollection('posts'); --- <ul> {posts.map(post => ( <li>{post.data.title}</li> ))} </ul>
import { getCollection } from 'astro:content'; const products = await getCollection('products'); --- <div> {products.map(product => ( <div> <h2>{product.data.name}</h2> <p>Price: ${product.data.price}</p> </div> ))} </div>
import { getCollection } from 'astro:content'; const events = await getCollection('events'); --- <section> <h1>Upcoming Events</h1> <ul> {events.map(event => ( <li>{event.data.date} - {event.data.title}</li> ))} </ul> </section>
getCollection from 'astro:content' to get the collection data..map() to display each item.Astro.fetchContent do in rendering collection content?posts in Astro to render each item?.map() returns a new array of elements for rendering.forEach does not return an array, so it won't render correctly. loop and each are not valid JavaScript array methods.products with items [{name: 'Pen'}, {name: 'Book'}], what will this Astro code output?{products.map(p => `${p.name}
`).join('')}Pen
', 'Book
'].Pen
Book
'.const items = Astro.fetchContent('items');
return items.map(item => <li>{item.name}</li>);published flag set to true. Which Astro code correctly fetches and renders only published posts from the blogs collection?await with Astro.fetchContent to get the posts array.filter(post => post.published) to keep only published posts, then map to render.Pass the test and this pattern moves unknown