/

Building Composable Layouts in Astro - Simplify Your Website Structure

Building Composable Layouts in Astro - Simplify Your Website Structure

When working on a website, it’s important to have the ability to divide layouts into separate files. This not only improves organization but also helps avoid the hassle of duplication and makes global changes easier.

Traditionally, creating a landing page or another page with a similar structure would involve duplicating code and making individual changes. However, static site builders like Astro offer a solution to this problem.

In Astro, layout composition is based on components. We can import and embed components in JSX to achieve a modular structure for our website. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
---
import Header from '../components/Header.astro'
import Footer from '../components/Footer.astro'
---
<html>
<body>
<Header />
<h1>A page</h1>
<Footer />
</body>
</html>

By creating reusable components, we can avoid code duplication. However, there’s still some HTML that gets duplicated across multiple pages. To address this, Astro provides a solution called layouts.

Layouts can be created in the src/layouts folder. For example:

1
2
3
4
5
6
7
8
9
10
11
---
import Header from '../components/Header.astro'
import Footer from '../components/Footer.astro'
---
<html>
<body>
<Header />
<slot />
<Footer />
</body>
</html>

Note the use of <slot />. It allows us to embed anything within the layout, including other components.

To utilize a layout, we simply import it into our page:

1
2
3
4
5
6
---
import MyLayout from '../layouts/MyLayout.astro'
---
<MyLayout>
<h1>Homepage!</h1>
</MyLayout>

By using layouts and components effectively, we can create a more modular, composable, and maintainable website structure in Astro.

tags: [“Astro”, “static site builder”, “composable layouts”, “website structure”]