Las Sections son bloques de contenido reutilizables que los editores pueden insertar en cualquier contenido mediante comandos slash. Úsalas para patrones comunes como CTAs, testimonios, cuadrículas de características o cualquier contenido que aparezca en múltiples páginas.
Consultar Sections
getSection
El siguiente ejemplo obtiene una sección única por slug:
import { getSection } from "emdash";
const cta = await getSection("newsletter-cta");
if (cta) {
console.log(cta.title); // "Newsletter CTA"
console.log(cta.content); // PortableTextBlock[]
}
getSections
El siguiente ejemplo obtiene múltiples sections con filtros opcionales:
import { getSections } from "emdash";
// Get all sections
const { items: all } = await getSections();
// Filter by source
const { items: themeSections } = await getSections({ source: "theme" });
// Search by title/keywords
const { items: results } = await getSections({ search: "newsletter" });
getSections devuelve { items: Section[], nextCursor?: string } siguiendo el patrón de paginación estándar.
Estructura de Section
Una section tiene la siguiente forma:
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;
}
Tipos de origen
| Source | Description |
|---|---|
theme | Definida en archivo seed, administrada por tema |
user | Creada por editores en el admin |
import | Importada desde WordPress (bloques reutilizables) |
Usar Sections en el contenido
Los editores insertan sections usando el comando slash /section en el editor de texto enriquecido.
-
Escribe
/section(o/pattern,/block,/template) -
Busca o explora las sections disponibles
-
Haz clic para insertar el contenido de la section en la posición del cursor
El contenido Portable Text de la section se copia en el documento. El contenido insertado es independiente: los editores pueden personalizarlo, y los cambios posteriores en la section no afectan las copias ya colocadas en el contenido.
Crear Sections
En la interfaz de administración
-
Navega a Sections en la barra lateral del admin
-
Haz clic en New Section
-
Completa:
- Title - Nombre para mostrar de la section
- Slug - Identificador de URL (generado automáticamente desde el título)
- Description - Texto de ayuda para editores
-
Agrega contenido usando el editor de texto enriquecido
-
Opcionalmente establece palabras clave para facilitar el descubrimiento
Mediante archivos Seed
El siguiente archivo seed define dos sections para un tema:
{
"sections": [
{
"slug": "hero-centered",
"title": "Centered Hero",
"description": "Full-width hero with centered heading and CTA",
"keywords": ["hero", "banner", "header"],
"content": [
{
"_type": "block",
"style": "h1",
"children": [{ "_type": "span", "text": "Welcome to Our Site" }]
},
{
"_type": "block",
"children": [{ "_type": "span", "text": "Your tagline goes here." }]
}
]
},
{
"slug": "newsletter-cta",
"title": "Newsletter CTA",
"keywords": ["newsletter", "subscribe", "email"],
"content": [
{
"_type": "block",
"style": "h3",
"children": [{ "_type": "span", "text": "Subscribe to our newsletter" }]
}
]
}
]
}
Mediante importación de WordPress
Los bloques reutilizables de WordPress (tipo de post wp_block) se importan automáticamente como sections:
- Source se establece en
"import" - El contenido de Gutenberg se convierte a Portable Text
Renderizar Sections programáticamente
El siguiente ejemplo renderiza el contenido de una section del lado del servidor, fuera del editor:
---
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>
)}
Características de la interfaz de administración
La biblioteca de Sections (/_emdash/admin/sections) proporciona:
- Vista de cuadrícula con vistas previas de sections
- Búsqueda por título y palabras clave
- Filtro por origen
- Copia rápida del slug al portapapeles
- Editar contenido y metadatos de la section
- Eliminar con confirmación (advierte para sections de tema)
Referencia de API
getSection(slug)
Obtén una section por slug.
Parámetros:
slug— El identificador único de la section (string)
Devuelve: Promise<Section | null>
getSections(options?)
Lista sections con filtros opcionales.
Parámetros:
options.source— Filtrar por origen:"theme","user"o"import"options.search— Buscar en título, descripción y palabras claveoptions.limit— Tamaño de página (predeterminado 50, máximo 100)options.cursor— Cursor de paginación de unnextCursoranterior
Devuelve: Promise<{ items: Section[]; nextCursor?: string }>
REST API
Listar Sections
Lista sections, opcionalmente filtradas por origen o término de búsqueda:
GET /_emdash/api/sections
GET /_emdash/api/sections?source=theme
GET /_emdash/api/sections?search=newsletter
Obtener Section
Obtén una sección única por slug:
GET /_emdash/api/sections/newsletter-cta
Crear Section
Crea una section con una petición POST:
POST /_emdash/api/sections
Content-Type: application/json
{
"slug": "my-section",
"title": "My Section",
"description": "Optional description",
"keywords": ["keyword1", "keyword2"],
"content": [...]
}
Actualizar Section
Actualiza una section con una petición PUT:
PUT /_emdash/api/sections/my-section
Content-Type: application/json
{
"title": "Updated Title",
"content": [...]
}
Eliminar Section
Elimina una section por slug:
DELETE /_emdash/api/sections/my-section
Próximos pasos
- Trabajar con contenido - Aprende sobre el editor de texto enriquecido
- Widget Areas - Para contenido dinámico sincronizado
- Importación de contenido - Importar bloques reutilizables de WordPress