Add BlogPost component and update blog and tag pages to display posts dynamically

This commit is contained in:
Thuan Bui
2026-01-02 14:37:49 +07:00
parent 2289c0cf44
commit 1724b6f49e
4 changed files with 66 additions and 4 deletions
+8
View File
@@ -0,0 +1,8 @@
---
const { url } = Astro.props;
const { title } = Astro.props;
---
<li>
<a href={url}>{title}</a>
</li>
+9 -4
View File
@@ -1,14 +1,19 @@
--- ---
import BaseLayout from "../layouts/BaseLayout.astro"; import BaseLayout from "../layouts/BaseLayout.astro";
import "../styles/global.css"; import BlogPost from "../layouts/BlogPost.astro";
const allPosts = Object.values(
import.meta.glob("./posts/*.md", { eager: true })
);
const pageTitle = "Blog"; const pageTitle = "Blog";
--- ---
<BaseLayout pageTitle={pageTitle}> <BaseLayout pageTitle={pageTitle}>
<p>This is where I will post about my journey learning Astro.</p> <p>This is where I will post about my journey learning Astro.</p>
<ul> <ul>
<li><a href='/posts/post-1/'>Post 1</a></li> {
<li><a href='/posts/post-2/'>Post 2</a></li> allPosts.map((post: any) => (
<li><a href='/posts/post-3/'>Post 3</a></li> <BlogPost url={post.url} title={post.frontmatter.title} />
))
}
</ul> </ul>
</BaseLayout> </BaseLayout>
+12
View File
@@ -0,0 +1,12 @@
---
layout: ../../layouts/MarkdownPostLayout.astro
title: My Fourth Blog Post
author: Astro Learner
description: "This post will show up on its own!"
image:
url: "https://docs.astro.build/default-og-image.png"
alt: "The word astro against an illustration of planets and stars."
pubDate: 2022-08-08
tags: ["astro", "successes"]
---
This post should show up with my other blog posts, because `import.meta.glob()` is returning a list of all my posts in order to create my list.
+37
View File
@@ -0,0 +1,37 @@
---
import BaseLayout from "../../layouts/BaseLayout.astro";
import BlogPost from "../../layouts/BlogPost.astro";
export async function getStaticPaths() {
const allPosts = Object.values(
import.meta.glob("../posts/*.md", { eager: true })
);
const uniqueTags = [
...new Set(allPosts.map((post: any) => post.frontmatter.tags).flat()),
];
return uniqueTags.map((tag) => {
const filteredPosts = allPosts.filter((post: any) =>
post.frontmatter.tags.includes(tag)
);
return {
params: { tag },
props: { posts: filteredPosts },
};
});
}
const { tag } = Astro.params;
const { posts } = Astro.props;
---
<BaseLayout pageTitle={tag}>
<p>Posts tagged with {tag}</p>
<ul>
{
posts.map((post: any) => (
<BlogPost url={post.url} title={post.frontmatter.title} />
))
}
</ul>
</BaseLayout>