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

@ -4,24 +4,40 @@ import FormattedDate from '../../components/FormattedDate.astro';
import SectionContainer from '../../components/SectionContainer.astro'; 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 => (
<ul> <section>
{ <div class="text-xl font-semibold">{year}</div>
posts.map((post) => ( <ul>
<li> {
<FormattedDate date={post.data.pubDate} /> postsByYear[year].map((post) => (
<a href={`/blog/${post.slug}/`}>{post.data.title}</a> <div class="flex justify-between mb-2 break-words">
</li> <a class="font-semibold" href={`/blog/${post.slug}/`}>✨ {post.data.title}</a>
)) <FormattedDate date={post.data.pubDate} />
} </div>
</ul> ))
</section> }
</ul>
</section>
))}
</main> </main>
</SectionContainer> </SectionContainer>