blogposts now sorted by year

This commit is contained in:
Sindre Kjelsrud 2023-12-09 21:29:54 +01:00
parent 86143c858a
commit cee2a73fac

View file

@ -6,22 +6,38 @@ import SectionContainer from '../../components/SectionContainer.astro';
const posts = (await getCollection('blog')).sort( const posts = (await getCollection('blog')).sort(
(a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf() (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
); );
// Group posts by year
const postsByYear = posts.reduce((acc, post) => {
const year = new Date(post.data.pubDate).getFullYear();
if (!acc[year]) {
acc[year] = [];
}
acc[year].push(post);
return acc;
}, {});
// Sort the years
const sortedYears = Object.keys(postsByYear).sort((a, b) => b - a);
--- ---
<SectionContainer> <SectionContainer>
<main class="flex flex-col h-screen gap-4 mt-4"> <main class="flex flex-col h-screen gap-4 mt-4">
<h1 class="text-4xl font-extrabold">Blog posts</h1> <h1 class="text-4xl font-extrabold">Blog posts</h1>
<section class="mt-4"> {sortedYears.map(year => (
<section>
<div class="text-xl font-semibold">{year}</div>
<ul> <ul>
{ {
posts.map((post) => ( postsByYear[year].map((post) => (
<li> <div class="flex justify-between mb-2 break-words">
<a class="font-semibold" href={`/blog/${post.slug}/`}>✨ {post.data.title}</a>
<FormattedDate date={post.data.pubDate} /> <FormattedDate date={post.data.pubDate} />
<a href={`/blog/${post.slug}/`}>{post.data.title}</a> </div>
</li>
)) ))
} }
</ul> </ul>
</section> </section>
))}
</main> </main>
</SectionContainer> </SectionContainer>