Build your first layout
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Mach dich bereit, …
- Refactor common elements into a page layout
- Use an Astro
<slot />
element to place page contents within a layout - Pass page-specific values as props to its layout
You still have some Astro components repeatedly rendered on every page. It’s time to refactor again to create a shared page layout!
Create your first layout component
Section titled Create your first layout component-
Create a new file at the location
src/layouts/BaseLayout.astro
. (You will need to create a newlayouts
folder first.) -
Copy the entire contents of
index.astro
into your new file,BaseLayout.astro
.
Use your layout on a page
Section titled Use your layout on a page-
Replace the code at
src/pages/index.astro
with the following: -
Check the browser preview again to notice what did (or, spoiler alert: did not!) change.
-
Add a
<slot />
element tosrc/layouts/BaseLayout.astro
just above the footer component, then check the browser preview of your Home page and notice what really did change this time!
The <slot />
allows you to inject (or “slot in”) child content written between opening and closing <Component></Component>
tags to any Component.astro
file.
Pass page-specific values as props
Section titled Pass page-specific values as props-
Pass the page title to your layout component from
index.astro
using a component attribute: -
Change the script of your
BaseLayout.astro
layout component to receive a page title viaAstro.props
instead of defining it as a constant. -
Check your browser preview to verify that your page title has not changed. It has the same value, but is now being rendered dynamically. And now, each individual page can specify its own title to the layout.
Try it yourself - Use your layout everywhere
Section titled Try it yourself - Use your layout everywhereRefactor your other pages (blog.astro
and about.astro
) so that they use your new <BaseLayout>
component to render the common page elements.
Don’t forget to:
-
Pass a page title as props via a component attribute.
-
Let the layout be responsible for the HTML rendering of any common elements.
-
Delete anything from each page that is no longer responsible for rendering, because it is being handled by the layout, including:
- HTML elements
- Components and their imports
- CSS rules in a
<style>
tag (e.g.<h1>
in your About page) <script>
tags
Test your knowledge
Section titled Test your knowledge-
An Astro component (
.astro
file) can function as a: -
To display a page title on the page, you can:
-
Information can be passed from one component to another by: