页面布局

本页内容

让编辑者选择一个页面模板,例如 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 中的另一项。