From e014d80a0f326af221d2dbb0d3dec9f2e09fb1bf Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Tue, 5 Aug 2025 23:50:58 +0200 Subject: [PATCH] docs: add canary docs for modifications (#3173) Adds v2 version of "Modyfing the " example. This is the next to last page that needs to be updated (though the other only requires minor changes to types). --- docs/canary/advanced/define.md | 2 + docs/canary/examples/modifying-the-head.md | 195 +++++++++++++++++++++ docs/toc.ts | 2 +- www/islands/TableOfContents.tsx | 14 +- www/utils/markdown.ts | 3 +- 5 files changed, 212 insertions(+), 4 deletions(-) create mode 100644 docs/canary/examples/modifying-the-head.md diff --git a/docs/canary/advanced/define.md b/docs/canary/advanced/define.md index 3842e372..06e4934c 100644 --- a/docs/canary/advanced/define.md +++ b/docs/canary/advanced/define.md @@ -30,6 +30,8 @@ export async function otherMiddleware(ctx: Context): Promise { With define helpers: ```ts util.ts +import { createDefine } from "fresh"; + // Setup, do this once in a file and import it everywhere else. export const define = createDefine<{ foo: string }>(); ``` diff --git a/docs/canary/examples/modifying-the-head.md b/docs/canary/examples/modifying-the-head.md new file mode 100644 index 00000000..a7a8e084 --- /dev/null +++ b/docs/canary/examples/modifying-the-head.md @@ -0,0 +1,195 @@ +--- +description: | + Modify content by passing state between AppWrapper/Layout and routes. +--- + +It's a common requirement for specific pages to need changes to content inside +the `` tag. + +- Setting the document title using `` +- Specifying page metadata using `<meta>` +- Linking to resources like stylesheets using `<link>` +- Including third-party JavaScript code using `<script>` + +## App Wrapper with State + +The recommended way to modify content in `<head>` is to use an app wrapper in +combination with `Context.state`. + +### 1. State + +The first step can be to define the possible state available on `Context`. In +this example, the `State` is very general to allow very flexible usage. + +```ts util.ts +import { createDefine } from "fresh"; +import type { JSX } from "preact"; + +export interface State { + title?: string; + metas?: JSX.IntrinsicElements["meta"][]; + links?: JSX.IntrinsicElements["link"][]; + scripts?: JSX.IntrinsicElements["script"][]; +} + +export const define = createDefine<State>(); +``` + +### 2. App wrapper + +After defining the State, create the App Wrapper to render the HTML with the +provided State. + +```tsx routes/_app.tsx +import { define } from "../util.ts"; + +export default define.page(function AppWrapper(ctx) { + const { title, links, metas, scripts } = ctx.state; + + return ( + <html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>{title ? `${title} | My App` : "My App"} + + {metas?.map((attrs, i) => )} + {links?.map((attrs, i) => )} + {scripts?.map((attrs, i) =>