記事を新しい方から表示する

(2024-03-28)

記事は新しい方を上に持ってきたいものです。

blog.astro の編集

結論ですが、blog.astro を以下のように変更します。

/src/pages/blog.astro
---
import BaseLayout from '../layouts/BaseLayout.astro'
import '../styles/global.css';
const allPosts = await Astro.glob('../pages/posts/*.md').then(posts => posts.reverse());
const nonDraftPosts = allPosts.filter((post) => !post.frontmatter.draft);
// ↓以下のコードに変更↓
const sortedPosts = nonDraftPosts.sort((a, b) => {
const aDate = new Date(a.frontmatter.pubDate);
const bDate = new Date(b.frontmatter.pubDate);
return bDate.getTime() - aDate.getTime();
});
const pageTitle = "Blog";
---
<BaseLayout pageTitle={pageTitle}>
<ul>
{nonDraftPosts.map((post) =>
<li class="border-b border-gray-400 mb-2 pb-2 hover:text-orange-700 transition-all duration-300">
<span class="text-slate-500 text-sm">{post.frontmatter.pubDate.slice(0,10)}</span><br>
<span class="text-lg"><a href={post.url}>{post.frontmatter.title}</a></span>
</li>)}
</ul>
</BaseLayout>
https://evoworx.dev/blog/astro-sorted-posts/

これは 100 年考えても自力では無理ですね。