區塊(Sections)

本頁內容

區塊(Sections)是可重複使用的內容區塊,編輯者可在任何內容中透過斜線指令插入。適用於 CTA、客戶推薦、功能網格等需要在多頁出現的模式。

查詢區塊

getSection

依 slug 取得單一區塊:

import { getSection } from "emdash";

const cta = await getSection("newsletter-cta");

if (cta) {
  console.log(cta.title);
  console.log(cta.content);
}

getSections

依條件取得多個區塊:

import { getSections } from "emdash";

const { items: all } = await getSections();
const { items: themeSections } = await getSections({ source: "theme" });
const { items: results } = await getSections({ search: "newsletter" });

getSections 會回傳 { items: Section[], nextCursor?: string },遵循常見分頁模式。

資料結構

interface Section {
  id: string;
  slug: string;
  title: string;
  description?: string;
  keywords: string[];
  content: PortableTextBlock[];
  previewUrl?: string;
  source: "theme" | "user" | "import";
  themeId?: string;
  createdAt: string;
  updatedAt: string;
}

來源類型

來源說明
theme在種子檔中定義,由主題管理
user在後台由編輯者建立
import從 WordPress 匯入(可重複使用區塊)

在內容中使用

編輯者在富文字編輯器中輸入 /section 插入:

  1. 輸入 /section(或 /pattern/block/template

  2. 搜尋或瀏覽可用區塊

  3. 點擊在游標位置插入該區塊內容

區塊的 Portable Text 會複製到文件中,因此:

  • 之後修改區塊不會影響已插入的內容
  • 編輯者可自行調整已插入內容
  • 內容保持自洽

建立區塊

在後台

  1. 在側邊欄進入 Sections

  2. 點擊 New Section

  3. 填寫 TitleSlugDescription

  4. 在富文字編輯器中新增內文

  5. 選填:keywords 以利搜尋

透過種子檔

在主題種子中包含 sections 陣列(JSON 範例與英文文件相同)。

WordPress 匯入

可重複使用區塊(wp_block)會匯入為區塊,source"import",Gutenberg 內容轉為 Portable Text。

在程式中算繪

---
import { getSection } from "emdash";
import { PortableText } from "emdash/ui";

const newsletter = await getSection("newsletter-cta");
---

{newsletter && (
  <aside class="cta-box">
    <PortableText value={newsletter.content} />
  </aside>
)}

後台功能

/_emdash/admin/sections 提供網格預覽、依標題/關鍵字搜尋、依來源篩選、複製 slug、編輯與刪除(主題區塊刪除時會提示)。

API 參考

getSection(slug)

參數: slug(string)。傳回: Promise<Section | null>

getSections(options?)

參數: sourcesearch傳回: Promise<Section[]>

REST API

與英文文件相同的 GET / POST / PUT / DELETE 路徑與 JSON 範例。

下一步