讓編輯者從編輯器的下拉選單中為每個頁面選擇佈局(例如預設、全寬、著陸頁),使用映射到頁面路由中佈局元件的 select 欄位。
運作方式
- 向頁面集合新增
template選擇欄位 - 為每個選項建立佈局元件
- 在頁面路由中將欄位值映射到佈局
這使用了 EmDash 的選擇欄位和 Astro 的元件模型。
新增欄位
在管理介面中,向頁面集合新增一個帶有 slug template 和佈局選項(例如 “Default”、“Full Width”)的選擇欄位。或者將其包含在種子資料中:
{
"slug": "template",
"label": "Template",
"type": "select",
"validation": {
"options": ["Default", "Full Width"]
},
"defaultValue": "Default"
}
建立佈局元件
每個佈局以不同的樣式包裝基礎佈局中的內容:
---
import type { ContentEntry } from "emdash";
import { PortableText } from "emdash/ui";
import Base from "./Base.astro";
interface Props {
page: ContentEntry<any>;
}
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 } from "emdash";
import { PortableText } from "emdash/ui";
import Base from "./Base.astro";
interface Props {
page: ContentEntry<any>;
}
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 { getEmDashEntry } from "emdash";
import PageDefault from "../../layouts/PageDefault.astro";
import PageFullWidth from "../../layouts/PageFullWidth.astro";
const { slug } = Astro.params;
if (!slug) {
return Astro.redirect("/404");
}
const { entry: page } = await getEmDashEntry("pages", slug);
if (!page) {
return Astro.redirect("/404");
}
const layouts = {
"Default": PageDefault,
"Full Width": PageFullWidth,
};
const Layout = layouts[page.data.template as keyof typeof layouts] ?? PageDefault;
---
<Layout page={page} />
路由保持精簡。每個佈局元件擁有自己的標記和樣式。新增佈局就是:建立元件,向選擇欄位新增選項,向映射新增一行。
新增更多佈局
常見的佈局選擇:
- Default — 窄內容欄,適合閱讀
- Full Width — 更寬的內容區域,無側邊欄
- Landing Page — 無頁首/頁尾,主打區域
- Sidebar — 帶有側邊欄小工具區域的內容
每個都只是 src/layouts/ 目錄中的另一個 Astro 元件,以及路由佈局映射中的另一個條目。