页面布局

本页内容

让编辑者选择一个页面模板,例如 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 组件,以及路由布局映射中的又一个条目。