內容頁面建立程序
逐步建立內容驅動頁面的程序,使用 Astro Content Collections (Content Layer API) 搭配動態路由。
先決條件
src/styles/global.css存在,且包含設計 Token(由 css-procedure 建立)docs/stitch/reference.md存在(包含來自 Stitch 螢幕的欄位資訊)
輸入 / 輸出
[輸入] [輸出]
docs/stitch/reference.md ──┐
(螢幕欄位資訊) │
progress.md 筆記 ──────────────┼──→ src/content/config.ts (架構定義)
(區塊結構、設計決策) │ src/content/<collection>/<slug>/index.mdx (資料)
│ src/pages/<collection>/[...slug].astro (路由)
│ src/components/*.astro (區塊元件)
步驟
步驟 1:定義架構 (src/content/config.ts)
Astro 5 Content Layer API 使用 glob 載入器。
1-1. 定義集合
import { defineCollection, z } from "astro:content";
import { glob } from "astro/loaders";
const myCollection = defineCollection({
loader: glob({ pattern: "**/index.mdx", base: "./src/content/my-collection" }),
schema: ({ image }) =>
z.object({
title: z.string(),
// ... 定義其他欄位
heroImage: image(), // 對圖片欄位使用 image() helper
}),
});
export const collections = { myCollection };
1-2. 結構設計指南
- 從最小化開始,逐步擴展。 只定義渲染當前頁面所需的欄位;在實作元件時再新增更多
- 對圖片欄位使用
image()helper,以啟用建置時的路徑驗證和最佳化 - 對非每個條目都必需的欄位使用
.optional() - 對區塊層級的資料使用可選陣列,以控制每個頁面的區塊可見性:
// 結構 moments: z.array(z.object({ title: z.string(), ... })).optional()<!-- 頁面範本:條件渲染 --> {data.moments && <MomentsSection moments={data.moments} />}
1-3. YAML Frontmatter 陷阱
- 月份名稱 (March, May 等) 和 Yes/No 會被 YAML 自動轉換。 如果希望它們是字串,請加上引號:
date: "March" - 圖片路徑是相對於 MDX 檔案的:
heroImage: ./hero.jpg
步驟 2:建立內容資料
2-1. 目錄結構
src/content/<collection>/<slug>/
├── index.mdx # frontmatter + MDX 本文
├── hero.jpg # 圖片與內容放在同一目錄
└── ...
2-2. MDX 檔案結構
---
title: "頁面標題"
heroImage: ./hero.jpg
description: "描述文字"
---
## MDX 本文
本文內容透過 `render()` 取得,並以 `<Content />` 進行渲染。
2-3. 圖片管理
- 將圖片存放在
src/content/中,與其內容放在一起(不要放在public/) - 在提交前,將大於 2560px 的圖片調整大小
- 在結構中使用
image()helper 時,frontmatter 中的圖片路徑會解析為ImageMetadata類型。元件 Props 也請使用ImageMetadata類型
步驟 3:動態路由頁面
建立 src/pages/<collection>/[...slug].astro:
---
import type { GetStaticPaths } from "astro";
import { getCollection, render } from "astro:content";
export const getStaticPaths = (async () => {
const items = await getCollection("myCollection");
return items.map((item) => ({
params: { slug: item.id },
props: { item },
}));
}) satisfies GetStaticPaths;
const { item } = Astro.props;
const { Content } = await render(item);
---
關鍵要點
getCollection()取得所有條目;getStaticPaths產生靜態路徑render()將 MDX 本文回傳為Content元件item.data提供對 frontmatter 欄位的類型安全存取- 對可選欄位使用條件渲染:
{data.field && <Component ... />}
步驟 4:頁面資料檔案 (src/data/<page>.md)
每個頁面上使用者可編輯的內容(文字、標籤、網址)應在 src/data/ 目錄下以帶有 YAML frontmatter 的 Markdown 檔案定義。這樣可以保持與 Content Collections 一致的格式,並讓使用者易於找到和編輯內容。
注意:
src/data/目錄並非由 Scaffold 技能建立。請在此步驟中建立它。
4-1. 為每個頁面建立資料檔案
src/data/
├── index.md # 作品集(頂層)頁面內容
├── about.md # 關於我頁面內容
└── skills.md # 技能頁面內容
4-2. 將可編輯內容定義為 YAML frontmatter
---
# ==============================
# 作品集頁面內容
# 編輯此檔案以自訂您的頁面。
# ==============================
hero:
headingPrefix: "嗨,我是一位"
highlightedText: "網頁開發者。"
description: "我構建可擴展、以使用者為中心的應用程式..."
badgeText: "可接新專案"
cta:
heading: "準備好一起打造些什麼了嗎?"
description: "我目前正在接洽自由接案機會..."
buttons:
- label: "聯絡我"
href: "mailto:[email protected]"
variant: "primary"
- label: "下載履歷"
href: "#"
variant: "secondary"
---
- 僅將使用者可編輯的文字放入 YAML(字串、標籤、網址、文字陣列)
- 將不可編輯的資料(如 SVG 圖示路徑)作為 TypeScript 常數保留在
.astro頁面檔案中
4-3. 在頁面中匯入資料
使用 import.meta.glob() 載入 frontmatter:
---
const content = Object.values(
import.meta.glob("../data/index.md", { eager: true })
)[0] as { frontmatter: Record<string, unknown> };
const { hero, cta } = content.frontmatter;
---
步驟 5:實作區塊元件
將每個區塊(hero、moments 等)建立為 src/components/ 中的獨立元件。
請遵循 develop-guideline 中有關元件結構和 CSS 規則的說明。
圖片顯示:<Picture> 與 <img>
| 方法 | 使用時機 | 範例 |
|---|---|---|
<Picture> | 在建置時已知的靜態圖片 | Hero 背景、條目圖片 |
<img> | 由客戶端 JavaScript 動態切換的圖片 | Modal 圖庫幻燈片 |
<Picture> 在建置時進行渲染,因此當 src 由客戶端 JS 切換時無法使用。
客戶端 JavaScript
Astro 元件中的 <script> 標籤會以客戶端 JS 方式執行。互動功能無需框架(React 等)即可建置。
資料傳遞模式: 使用 data-* 屬性將 frontmatter 資料傳遞給客戶端 JS。<script> 無法直接引用 frontmatter 變數。
無障礙性:Modal / 覆蓋層
Modal 對話框實作的檢查清單:
| 需求 | 實作方式 |
|---|---|
| 語意 | role="dialog" + aria-modal="true" + aria-label |
| 開啟/關閉 | 切換 hidden 屬性 + CSS opacity 轉場 |
| 滾動鎖定 | 開啟:document.body.style.overflow = "hidden" / 關閉:恢復為 "" |
| 鍵盤 | Escape 關閉,方向鍵進行導航 |
| 焦點鎖定 | Tab/Shift+Tab 在 modal 內的按鈕間循環 |
| 焦點恢復 | 關閉時對觸發元素執行 focus() |
| 背景關閉 | 當點擊目標不是互動元素時關閉 |
| z-index | 高於現有的固定定位元素(例如 header 50 → modal 60) |
步驟 6:建置驗證
npm run build
Content Collections 的結構驗證錯誤會在建置時顯示,並附帶清晰的訊息。
常見錯誤
| 錯誤 | 原因 | 修正 |
|---|---|---|
Expected type "string", received "object" | YAML 自動轉換了某個值(月份名稱 → Date 等) | 將該值加上引號 |
Could not find image | 圖片路徑不正確 | 驗證從 MDX 檔案出發的相對路徑 |
does not match collection schema | frontmatter 中缺少欄位或類型不符 | 對照 config.ts 中的結構進行檢查 |
步驟 7:開發伺服器驗證
npm run dev
- 結構變更可能需要重新啟動開發伺服器(清除內容儲存區)
- 如果重新啟動後錯誤仍然存在,請刪除
.astro/目錄並重新啟動
檢查清單
-
src/content/config.ts已定義結構 - MDX frontmatter 符合結構定義
- 圖片位於
src/content/內,且已調整大小至 ≤2560px -
[...slug].astro從getStaticPaths回傳所有條目 - 可選欄位的區塊使用條件渲染
-
npm run build成功執行 - 在瀏覽器中視覺確認所有區塊(包含行動裝置寬度)