頁面版面

本頁內容

讓編輯者選擇一個頁面範本,例如 Default、Full Width 或 Landing Page。select 欄位儲存這項選擇,頁面路由再把該值對映到一個 Astro 版面元件。如果編輯者需要在同一個頁面內組合並重新排列多個區塊,請使用 blocks 欄位。

運作方式

  1. 向頁面集合新增一個 template 選擇欄位
  2. 為每個選項建立版面元件
  3. 在頁面路由中把欄位值對映到版面

這利用了 EmDash 的選擇欄位和 Astro 的元件模型。

新增欄位

在管理介面中,向頁面集合新增一個 slug 為 template 的選擇欄位,並填入你的版面選項(例如「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.rewrite("/404");
}

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

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

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

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

<Layout page={page} />

路由保持精簡。每個版面元件各自負責自己的標記和樣式。新增一個版面只需三步:建立一個元件,把選項新增到選擇欄位,再在對映中加一行。

新增更多版面

常見的版面選擇:

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

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