Customizing an Astro blog
A few code snippets for your astro blog
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.
<ul>
{posts.mappost =>
<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 : postscurrentPostIndex + 1;
const nextPost = currentPostIndex === 0 ? undefined : postscurrentPostIndex - 1;
---
{
previousPost || nextPost &&
<nav>
{ previousPost && <p><a href={`/posts/${previousPost.id}/`}>{previousPost.data.title}</a></p> }
{ nextPost && <p><a href={`/posts/${nextPost.id}/`}>{nextPost.data.title}</a></p> }
</nav>
}
Add the BlogPostNavPrevNext component to the page.
Import Meta Glob
Blog: Display recent posts and featured post.
{posts.slice0, 3.map(post) =>
<h3>{post.data.title}</h3>
<p>{post.data.pubDate.toLocaleDateString}</p>
<p>{post.data.description}</p>
<a href={`/posts/${post.id}/`}></a>
}Adding full content to RSS feed
Source: Add sanitize-html and markdown-it packages and insert below code into RSS file.
content: sanitizeHtmlparser.renderpost.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";togetCollection, 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();toconst { Content } = await render(post); - Change
feedItems.push({ ...post.data, link: /blog/${post.**slug**}/, content });topost.id
Now I have a feed that basically matches my Bearblog one!
More Resources: Pagination