#empty content collection
3 messages · Page 1 of 1 (latest)
Hi @green goblet. 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 handle an empty content collection by checking the length of the collection after fetching it. If the length is zero, you can display a message on your page. Here's an example of how you can do this:
---
import { getCollection } from 'astro:content';
const posts = await getCollection('posts');
---
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Astro</title>
</head>
<body>
<main>
<h1>Posts</h1>
<ul>
{
posts.length > 0 ?
posts.map((post) => (
<li>
<a href={`/posts/${post.slug}`}>{post.data.title}</a>
</li>
)) :
<li>No posts available</li>
}
</ul>
</main>
</body>
</html>
In this example, if the posts collection is empty, the message "No posts available" will be displayed on the page.
Please note that there is an open issue on Astro's GitHub regarding handling empty content collections. Currently, an empty content collection throws an error, but there is a suggestion to change this behavior to throw a warning instead of an error. You can follow the discussion here (https://github.com/withastro/astro/issues/8336).