頁面版面

本頁內容

讓編輯者選擇一個頁面範本,例如 Default、Full Width 或 Landing Page。select 欄位儲存該選擇,頁面路由將該值對應到 Astro 版面元件。當編輯者需要在同一頁面內組合並重排多個區段時,請使用 blocks 欄位。

運作方式

  1. 向 pages 集合新增 template select 欄位
  2. 為每個選項建立版面元件
  3. 在頁面路由中將欄位值對應到版面

這使用 EmDash 的 select 欄位與 Astro 的元件模型。

新增欄位

在管理 UI 中,向 pages 集合新增 slug 為 template 的 select 欄位及版面選項(例如「Default」和「Full Width」)。要在種子資料中定義同一欄位,請將以下物件新增到集合的 fields 陣列:

{
  "slug": "template",
  "label": "Template",
  "type": "select",
  "validation": {
    "options": ["Default", "Full Width"]
  },
  "defaultValue": "Default"
}

建立版面元件

每個版面以不同樣式將內容包在基礎版面中:

---
import type { ContentEntry, InferCollectionData } from "emdash";
import { PortableText } from "emdash/ui";
import Base from "./Base.astro";

interface Props {
  page: ContentEntry<InferCollectionData<"pages">>;
}

const { page } = Astro.props;
---

<Base title={page.data.title}>
  <article class="page-default">
    <h1>{page.data.title}</h1>
    <PortableText value={page.data.content} />
  </article>
</Base>

<style>
  .page-default {
    max-width: var(--content-width);
    margin: 0 auto;
    padding: 2rem 1rem;
  }
</style>
---
import type { ContentEntry, InferCollectionData } from "emdash";
import { PortableText } from "emdash/ui";
import Base from "./Base.astro";

interface Props {
  page: ContentEntry<InferCollectionData<"pages">>;
}

const { page } = Astro.props;
---

<Base title={page.data.title}>
  <article class="page-wide">
    <h1>{page.data.title}</h1>
    <PortableText value={page.data.content} />
  </article>
</Base>

<style>
  .page-wide {
    max-width: var(--wide-width);
    margin: 0 auto;
    padding: 2rem 1rem;
  }
</style>

連接路由

在頁面路由中匯入每個版面並對應範本值:

---
import { decodeSlug, getEmDashEntry } from "emdash";
import PageDefault from "../../layouts/PageDefault.astro";
import PageFullWidth from "../../layouts/PageFullWidth.astro";

const slug = decodeSlug(Astro.params.slug);

if (!slug) {
  return Astro.redirect("/404");
}

const { entry: page } = await getEmDashEntry("pages", slug);

if (!page) {
  return Astro.redirect("/404");
}

const layouts = new Map([
  ["Default", PageDefault],
  ["Full Width", PageFullWidth],
]);

const Layout = layouts.get(page.data.template ?? "") ?? PageDefault;
---

<Layout page={page} />

路由保持精簡。每個版面元件擁有自己的標記與樣式。新增版面即:建立元件、向 select 欄位新增選項、向 map 新增一行。

新增更多版面

常見版面選擇:

  • Default — 窄內容欄,適合閱讀
  • Full Width — 更寬的內容區,無側邊欄
  • Landing Page — 無頁首/頁尾,英雄區塊
  • Sidebar — 旁側帶有小工具區域的內容

每個都只是 src/layouts/ 目錄中的另一個 Astro 元件,以及路由版面 map 中的另一項。