Page fragments
The page:fragments hook contributes scripts or raw HTML to the head or body of a rendered public page. Use it for browser code that structured metadata cannot express, such as an analytics loader with a <noscript> fallback.
Fragment output runs as first-party page code. EmDash invokes this hook only for trusted, in-process plugins; sandboxed plugins never contribute fragments. If the page needs meta tags, canonical or alternate links, or JSON-LD, use the sandbox-compatible page:metadata hook instead.
Declare the capability and hook
Section titled “Declare the capability and hook”page:fragments requires hooks.page-fragments:register in the native runtime definition. The following hook adds an external script and an HTML fallback only when a configured analytics ID exists:
return definePlugin({ id: "plugin-analytics", version: "0.1.0", capabilities: ["hooks.page-fragments:register"], hooks: { "page:fragments": async (event, ctx) => { const analyticsId = await ctx.settings.get<string>("analyticsId"); if (!analyticsId || event.page.path.startsWith("/_emdash/")) return null;
const encodedId = encodeURIComponent(analyticsId); return [ { kind: "external-script", placement: "head", src: `https://analytics.example.com/client.js?id=${encodedId}`, async: true, key: "analytics-client", }, { kind: "html", placement: "body:end", html: "<noscript>Analytics requires JavaScript.</noscript>", key: "analytics-fallback", }, ]; }, },});Raw HTML contributions are inserted verbatim. Keep the fragment static when possible; otherwise escape every value that can come from settings, content, request data, or an external service.
For native plugins, declare the capability in definePlugin(). The descriptor does not need a second copy because createPlugin() supplies the runtime capability list.
If the capability is missing, EmDash logs a warning and does not register the hook. Hook errors are logged and do not prevent the page from rendering.
Add the layout insertion points
Section titled “Add the layout insertion points”The host theme chooses which placements it supports. It must pass the same PublicPageContext to the corresponding EmDash components:
-
Build the page context once in the layout.
src/layouts/Base.astro ---import { createPublicPageContext } from "emdash/page";import {EmDashBodyEnd,EmDashBodyStart,EmDashHead,} from "emdash/ui";interface Props {title: string;description?: string;content?: { collection: string; id: string; slug?: string | null };}const { title, description, content } = Astro.props;const page = createPublicPageContext({Astro,kind: content ? "content" : "custom",pageType: content ? "article" : "website",title,description,content,});--- -
Render each supported placement in the matching part of the document.
src/layouts/Base.astro <html lang="en"><head><title>{title}</title><EmDashHead page={page} /></head><body><EmDashBodyStart page={page} /><slot /><EmDashBodyEnd page={page} /></body></html>