307 words
2 minutes
Adventures in making a blog part 2

After going through the Astro blog tutorial and adding my own css to it, I was quite satisfied with how it came out. However, there were a few things I wanted to incorporate with further help from the Astro docs and other resources. I will be adding to this as I progress.

Archive posts sorted by date with content collection:

const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);

The same method was applied to the tag pages, except with const allPosts instead.

HTML:

<ul>
{posts.map(post => (
<li>{post.data.pubDate.toLocaleDateString()}: <a href={`/posts/${post.id}`}>{post.data.title}</a></li>
))}
</ul>

Navigation between entries:

---
import { getCollection } from 'astro:content';
const posts = (await getCollection('blog'))
.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
const currentPostIndex = posts.findIndex((post) => post.id == Astro.params.slug);
const previousPost = currentPostIndex + 1 === posts.length ? undefined : posts[currentPostIndex + 1];
const nextPost = currentPostIndex === 0 ? undefined : posts[currentPostIndex - 1];
---
{
(previousPost || nextPost) && (
<nav>
{ previousPost && ( <p>Previous Post: <a href={`/posts/${previousPost.id}/`}>{previousPost.data.title}</a></p> ) }
{ nextPost && ( <p>Next Post: <a href={`/posts/${nextPost.id}/`}>{nextPost.data.title}</a></p> ) }
</nav>
)
}

Add the BlogPostNavPrevNext component to the page.

Import Meta Glob: Display recent posts and featured post.

{posts.slice(0, 3).map((post) => (
<h3>{post.data.title}</h3>
<p>{post.data.pubDate.toLocaleDateString()}</p>
<p>{post.data.description}</p>
<a href={`/posts/${post.id}/`}>Read more</a>
))}

Adding full content to RSS feed: Add sanitize-html and markdown-it packages and insert below code into RSS file.

content: sanitizeHtml(parser.render(post.body), {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img'])
}),
...post.data,

Edit: I ended up completely changing the RSS file to this one found on Github. I installed MDX and made the necessary changes for Astro 5:

  • Change import { getCollection } from "astro:content"; to getCollection, render
  • Remove import { SITE_DESCRIPTION, SITE_TITLE } from "../consts"; (I don’t have a consts folder on that blog)
  • Change const { Content } = await post.render(); to const { Content } = await render(post);
  • Change feedItems.push({ ...post.data, link: /blog/${post.**slug**}/, content }); to post.id

Now I have a feed that basically matches my Bearblog one!

More Resources: Pagination