创建数据并将其传递到自定义博客布局
现在你已经有了页面布局,是时候为博客文章添加布局了!
¥Now that you have a layout for your pages, it’s time to add a layout for blog posts!
Get ready to…
-
为你的 Markdown 文件创建新的博客文章布局
-
将 YAML frontmatter 值作为 props 传递给布局组件
为你的博客文章添加布局
Section titled 为你的博客文章添加布局¥Add a layout to your blog posts
当你在 .md
文件中包含 layout
frontmatter 属性时,所有 frontmatter YAML 值都可用于布局文件。
¥When you include the layout
frontmatter property in an .md
file, all of your frontmatter YAML values are available to the layout file.
-
Create a new file at
src/layouts/MarkdownPostLayout.astro
-
Copy the following code into
MarkdownPostLayout.astro
-
Add the following frontmatter property in
post-1.md
-
Check your browser preview again at
http://localhost:4321/posts/post-1
and notice what the layout has added to your page. -
Add the same layout property to your two other blog posts
post-2.md
andpost-3.md
. Verify in your browser that your layout is also applied to these posts.
自己尝试一下 - 自定义你的博客文章布局
Section titled 自己尝试一下 - 自定义你的博客文章布局¥Try it yourself - Customize your blog post layout
挑战:识别每篇博文中常见的项目,并使用 MarkdownPostLayout.astro
来渲染它们,而不是将它们写在 post-1.md
中的 Markdown 以及以后的每一篇博文中。
¥Challenge: Identify items common to every blog post, and use MarkdownPostLayout.astro
to render them, instead of writing them in your Markdown in post-1.md
and in every future blog post.
以下是重构代码以将 pubDate
包含在布局组件中而不是将其写入 Markdown 正文中的示例:
¥Here’s an example of refactoring your code to include the pubDate
in the layout component instead of writing it in the body of your Markdown:
尽可能多地重构你认为对你有用的内容,并根据需要向布局中添加尽可能多的内容,请记住,添加到布局中的所有内容都会让你在每篇博客文章中少写一件内容!
¥Refactor as much as you think is useful to you, and add as much to your layout as you want, remembering that everything that you add to your layout is one less thing you will write in each and every blog post!
下面是一个重构布局的示例,该布局仅留下由插槽渲染的单个博客文章内容。请随意使用它,或者创建你自己的!
¥Here is an example of a refactored layout that leaves only individual blog post content rendered by the slot. Feel free to use this, or create your own!
测试你的知识
Section titled 测试你的知识¥Test your knowledge
你能弄清楚空白处应该填什么,以便下面的两个组件一起生成工作的 Astro 代码吗?
¥Can you figure out what should go in the blanks so that the following two components together produce working Astro code?
Show the blanks filled in!
¥Checklist
¥Resources
-
YAML 简介 external