題目
- 在
src/pages/下建立一個新檔案about.astro。 - 匯入並使用剛才寫好的
BaseLayout。 - 在
---區塊內定義一個對象identity,包含firstName和hobbies(數組)。 - 在頁面上使用
{identity.firstName}顯示名字。 - 使用
{identity.hobbies.map()}把你的愛好列印成一個列表。 - 挑戰題: 試著在
BaseLayout裡增加一個變數,讓每個頁面的背景顏色可以透過 Props 從index.astro或about.astro傳進去(例如:index是白色,about是淺灰色)。
目前專案結構
📁 .astro/
📁 .vscode/
📁 node_modules/
📁 public/
└─ favicon.svg
📁 src/
├─ 📁 layouts/
│ └─ BaseLayout.astro
└─ 📁 pages/
└─ index.astro
.gitignore
astro.config.mjs
package-lock.json
package.json
README.md
tsconfig.json
1_新增 src/pages/about.astro
---
import BaseLayout from '../layouts/BaseLayout.astro'
const pageTitle = '關於我'
const identity = {
firstName: '小明',
hobbies: ['reading', 'gaming', 'coding'],
}
---
<BaseLayout pageTitle={pageTitle}>
<h2>{identity.firstName}</h2>
<h3>我的愛好</h3>
<ul>
{identity.hobbies.map((x) => <li>{x}</li>)}
</ul>
</BaseLayout>
2_挑戰題
2_1. 修改 src/layouts/BaseLayout.astro :
新增 pageName 變數作為判斷
新增class .bg-white、.bg-gray
---
const { pageTitle, pageName } = Astro.props
const _bodyClass =
pageName == 'index' ? 'bg-white' : pageName == 'about' ? 'bg-gray' : ''
---
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<title>{pageTitle}</title>
<style>
body {
font-family: sans-serif;
line-height: 1.6;
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
nav {
border-bottom: 1px solid #ccc;
padding-bottom: 1rem;
margin-bottom: 2rem;
}
a {
margin-right: 1rem;
text-decoration: none;
color: #0070f3;
}
.bg-white {
background: white;
}
.bg-gray {
background: rgb(235, 235, 235);
}
</style>
</head>
<body class={_bodyClass}>
<nav>
<a href="/">首頁</a>
<a href="/about">關於我</a>
</nav>
<h1>{pageTitle}</h1>
<slot />
<footer>
<hr />
<p>© 2024 我的 Astro 學習筆記</p>
</footer>
</body>
</html>
2_2. 修改 src/pages/index.astro :<BaseLayout> 加入 pageName="index"
---
import BaseLayout from '../layouts/BaseLayout.astro'
const pageTitle = '首頁'
const skills = ['Astro', 'TypeScript', 'React']
---
<BaseLayout pageTitle={pageTitle} pageName="index">
<h2>歡迎來到我的 Astro 課程</h2>
<p>這是我的第一個頁面,正在練習如何使用 Layout。</p>
<ul>
{skills.map((x) => <li>{x}</li>)}
</ul>
</BaseLayout>
2_3. 修改 src/pages/index.astro :<BaseLayout> 加入 pageName="about"
---
import BaseLayout from '../layouts/BaseLayout.astro'
const pageTitle = '關於我'
const identity = {
firstName: '小明',
hobbies: ['reading', 'gaming', 'coding'],
}
---
<BaseLayout pageTitle={pageTitle} pageName="about">
<h2>{identity.firstName}</h2>
<h3>我的愛好</h3>
<ul>
{identity.hobbies.map((x) => <li>{x}</li>)}
</ul>
</BaseLayout>
執行結果
npm run dev 後,會顯示 http://localhost:4321,使用這串網址可以查看效果











