Layout and Pages in Astro

Problems faced during installation:

Note: When I was practicing astro, I faced a certain problem in installing or creating astro project

  • When I installed astro project without agreeing the git initialization, it always throwed an error so I switched manual set up.

  • There was another way to create a new project in astro using following command:

      npm create astro@latest --template minimal
    

    For some reason it throws an error also and I needed project without git initialization, so I switched to manual set up

  • If you don’t have any problem with git Initialization, you can do with npm create astro@latest command.

Layouts and Pages in Astro:

I don’t exaggerate things describing about why there is package.json and why we have to design the components and pages inside src folder.

The major thing you need to know is that when you want design the project you have to do it inside the src folder. We have already created the file index.astro inside it. Let’s take another step understand how we can design pages using layouts.

Layout:

Layouts are structure of the web page. You might hear about layout in other frameworks, why we create layout?

Layout pages are created to create single page web applications.

Steps to Create Layout page:

  • Create a directory inside src directory and name it as layout.

  • Create a new astro file naming it as Layout.astro

  • Write the following code as follows

---

---
<html>
    <head>
        <title>title</title>
    </head>
    <body>
        <slot />
    </body>
</html>
<style>
    *{
        margin: 0;
        padding:0;
        box-sizing: border-box;
    }
</style>

The above code is a simple astro page with simple HTML.

<slot /> : This tag is used define the children elements that we pass inside are pages which we call it as web page.

Import Layout in a Page.

Open a page for example index.astro for now, There whatever the code you wrote just clean it and rewrite the below code:

---
import Layout from '../layout/Layout.astro';
---
<Layout>
    <h1> Hello Layout </h1>
</Layout>
<style>
    h1{
        color:red;
    }
</style>

here the Layout.astro became an element which renders the children elements in a Layout which we designed in Layout.astro.

The index.astro just import the Layout and render h1 element in the Layout.astro structure.

Thank you for reading this article. This is just a simple article about Layout and pages only.