覚書 (3)

ビュー的なやつ

本家の手順を飛ばして先にレイアウトを作る。

レイアウト

/src/layouts/BlogLayout.astro を作成する。ここで css をインポートする。

/src/layouts/BlogLayout.astro
---
import '../styles/style.css';
---

<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width" />
    <title></title>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
        </ul>
      </nav>
      <h1>ワイのAstro🚀Blog</h1>
    </header>
    <main>
      <slot />
    </main>
    <footer></footer>
  </body>
</html>

トップページ

/src/pages/index.astro を書き換える。

/src/pages/index.astro
---
import BlogLayout from '../layouts/BlogLayout.astro';
---

<BlogLayout>
  <p>ほーむぺーじ</p>
</BlogLayout>

タイトル

ページからレイアウトへタイトルを渡せるようにする。

<title> が空だと頭がおか*いと思われるので初期値を設定しておく。というか <title> 要素は空にしてはいけない。

/src/layouts/BlogLayout.astro
---
import '../styles/style.css';

interface Props { title?: string }
const { title = 'ワイのAstro🚀Blog' } = Astro.props;
---

<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width" />
    <title>{title}</title>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
        </ul>
      </nav>
      <h1>{title}</h1>
    </header>
    <main>
      <slot />
    </main>
    <footer></footer>
  </body>
</html>
/src/pages/index.astro
<BlogLayout title="Home">
  <p>ほーむぺーじ</p>
</BlogLayout>

レイアウトを分割する

必須ではないけど、細かくできるものは細かくしておいたほうがよい。

のように分割する。それぞれに <slot> を設置し、何かを挿入できるようにしておく。

/src/layouts/BlogLayout.astro
---
import Head from './Head.astro';
import Header from './Header.astro';
import Footer from './Footer.astro';
import '../styles/style.css';

interface Props { title?: string }
const { title = 'ワイのAstro🚀Blog' } = Astro.props;
---

<html lang="ja">
  <Head title={title} />
  <body>
    <Header title={title} />
    <main>
      <slot />
    </main>
    <Footer />
  </body>
</html>
/src/layouts/Head.astro
---
interface Props { title: string }
const { title } = Astro.props;
---

<head>
  <meta charset="utf-8" />
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
  <meta name="viewport" content="width=device-width" />
  <title>{title}</title>
  <slot />
</head>
/src/layouts/Header.astro
---
import Nav from './Nav.astro';

interface Props { title: string }
const { title } = Astro.props;
---

<header>
  <Nav />
  <h1>{title}</h1>
  <slot />
</header>
/src/layouts/Nav.astro
<nav>
  <ul>
    <li><a href="/">Home</a></li>
  </ul>
</nav>
/src/layouts/Footer.astro
<footer>
  <slot />
</footer>