Create and pass data to a custom blog layout
이 컨텐츠는 아직 번역되지 않았습니다.
Now that you have a layout for your pages, it’s time to add a layout for blog posts!
요구 사항
- Create a new blog post layout for your Markdown files
- Pass YAML frontmatter values as props to layout component
Add a layout to your blog posts
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.
When using layouts, you now have the option of including elements, like a page title, in the Markdown content or in the layout. Remember to visually inspect your page preview and make any adjustments necessary to avoid duplicated elements.
Try it yourself - Customize your blog post layout
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.
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!
Anything rendered by your layout does not need to be typed into your blog post! If you notice any duplication when you check your browser preview, then be sure to remove content from your Markdown file.
Test your knowledge
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!