Home / Log

Combine Collections in AstroJS

Expanding Your Astro Blog: Integrating Multiple Post Collections

As your blog grows, you might want to incorporate different types of content, such as guest posts, alongside your regular posts. Astro makes this process straightforward, allowing you to maintain multiple collections while presenting a unified blog experience to your readers. In this tutorial, we’ll walk through the process of integrating both regular posts and guest posts into your Astro blog.

Setting Up Multiple Collections

Before we dive into the code, ensure you have two collections set up in your src/content directory:

  1. posts: Your regular blog posts
  2. guestposts: Posts written by guest authors

Modifying […slug].astro

The key to integrating multiple collections lies in updating your /src/pages/blog/[...slug].astro file. Here’s how to do it:

1. Import Collections

Start by importing both collections at the top of your file:

---
import { getCollection } from 'astro:content'

const posts = await getCollection('posts')
const guestPosts = await getCollection('guestposts')
---

2. Combine Collections

Next, merge the two collections into a single array:

---
const allPosts = [...posts, ...guestPosts]
---

3. Update getStaticPaths

Modify the getStaticPaths function to use the combined collection:

---
export async function getStaticPaths() {
  const allPosts = [...posts, ...guestPosts]
  return allPosts.map((post) => ({
    params: { slug: post.slug },
    props: { post },
  }))
}

const { post } = Astro.props
---

4. Render Post Content

Finally, render the post content as usual:

---
const { Content } = await post.render()
---

<html>
  <head>
    <title>{post.data.title}</title>
  </head>
  <body>
    <h1>{post.data.title}</h1>
    <Content />
  </body>
</html>

Advanced Techniques

Distinguishing Post Types

To differentiate between regular and guest posts, you can add a conditional check:

---
const postType = post.collection === 'guestposts' ? 'Guest Post' : 'Regular Post'
---

<p>This is a {postType}</p>

Sorting Combined Posts

Ensure consistent sorting across all posts by using a common frontmatter property:

---
const allPosts = [...posts, ...guestPosts].sort(
  (a, b) => new Date(b.data.pubDate) - new Date(a.data.pubDate)
)
---

By following these steps, you can easily integrate multiple post collections into your Astro blog. This approach allows you to maintain separate content sources while presenting a unified blog experience to your readers. As your blog continues to grow, you can add more collections and adapt this method to suit your evolving needs.

Remember to update your blog index page and any other relevant components to reflect these changes. Happy blogging with Astro!

Date
16.08.2024
Categories
  • WebDev
  • AstroJS
Tags
  • WebDev
  • AstroJS