Create a blog post archive
本頁內容尚未翻譯。
Now that you have a few blog posts to link to, it’s time to configure the Blog page to create a list of them automatically!
Get ready to…
- Access data from all your posts at once using
import.meta.glob()
- Display a dynamically generated list of posts on your Blog page
- Refactor to use a
<BlogPost />
component for each list item
Dynamically display a list of posts
Section titled Dynamically display a list of posts-
Add the following code to
blog.astro
to return information about all your Markdown files.import.meta.glob()
will return an array of objects, one for each blog post. -
To generate the entire list of posts dynamically, using the post titles and URLs, replace your individual
<li>
tags with the following Astro code:Your entire list of blog posts is now being generated dynamically using Astro’s built-in TypeScript support, by mapping over the array returned by
import.meta.glob()
. -
Add a new blog post by creating a new
post-4.md
file insrc/pages/posts/
and adding some Markdown content. Be sure to include at least the frontmatter properties used below. -
Revisit your blog page in your browser preview at
http://localhost:4321/blog
and look for an updated list with four items, including your new blog post!
Challenge: Create a BlogPost component
Section titled Challenge: Create a BlogPost componentTry on your own to make all the necessary changes to your Astro project so that you can instead use the following code to generate your list of blog posts:
Expand to see the steps
-
Create a new component in
src/components/
.Show the filename
-
Write the line of code in your component so that it will be able to receive a
title
andurl
asAstro.props
.Show the code
-
Add the templating used to create each item in your blog post list.
Show the code
-
Import the new component into your Blog page.
Show the code
-
Check Yourself: see the finished component code.
Show the code
Test your knowledge
Section titled Test your knowledgeIf your Astro component contains the following line of code:
Choose the syntax you could write to represent:
-
The title of your third blog post.
-
A link to the URL of your first blog post.
-
A component for each post, displaying the date that it was last updated.