|
| 1 | +--- |
| 2 | +description: Modify the document head in Fresh |
| 3 | +--- |
| 4 | + |
| 5 | +The |
| 6 | +[`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head)-element |
| 7 | +is a crucial element in HTML to set metadata for a page. It allows you to: |
| 8 | + |
| 9 | +- Set the document title with `<title>` |
| 10 | +- Specify page metadata with `<meta>` |
| 11 | +- Link to resources like stylesheets with `<link>` |
| 12 | +- Include JavaScript code with `<script>` |
| 13 | + |
| 14 | +> [info]: The outer HTML structure including `<head>` is typically created |
| 15 | +> inside `_app.tsx`. |
| 16 | +
|
| 17 | +## Passing metadata from `ctx.state` |
| 18 | + |
| 19 | +For simple scenarios passing metadata along from a handler or a middleware by |
| 20 | +writing to `ctx.state` is often sufficient. |
| 21 | + |
| 22 | +```tsx routes/_app.tsx |
| 23 | +import { define } from "../util.ts"; |
| 24 | + |
| 25 | +export default define.page((ctx) => { |
| 26 | + return ( |
| 27 | + <html lang="en"> |
| 28 | + <head> |
| 29 | + <meta charset="utf-8" /> |
| 30 | + <title>{ctx.state.title ?? "Welcome!"}</title> |
| 31 | + </head> |
| 32 | + <body> |
| 33 | + <ctx.Component /> |
| 34 | + </body> |
| 35 | + </html> |
| 36 | + ); |
| 37 | +}); |
| 38 | +``` |
| 39 | + |
| 40 | +## Using the `<Head>`-component |
| 41 | + |
| 42 | +For more complex scenarios, or to set page metadata from islands, Fresh ships |
| 43 | +with the `<Head>`-component. |
| 44 | + |
| 45 | +```tsx routes/about.tsx |
| 46 | +import { Head } from "fresh/runtime"; |
| 47 | + |
| 48 | +export default define.page((ctx) => { |
| 49 | + return ( |
| 50 | + <div> |
| 51 | + <Head> |
| 52 | + <title>About me</title> |
| 53 | + </Head> |
| 54 | + <h1>About me</h1> |
| 55 | + <p>I like Fresh!</p> |
| 56 | + </div> |
| 57 | + ); |
| 58 | +}); |
| 59 | +``` |
| 60 | + |
| 61 | +### Avoiding duplicate tags |
| 62 | + |
| 63 | +You might end up with duplicate tags, when multiple `<Head />` components are |
| 64 | +rendered on the same page. Fresh will employ the following strategies to find |
| 65 | +the matching element: |
| 66 | + |
| 67 | +1. For `<title>` elements Fresh will set `document.title` directly |
| 68 | +2. Check if an element with the same `key` exists |
| 69 | +3. Check if an element with the same `id` attribute |
| 70 | +4. Only for `<meta>` elements: Check if there is a `<meta>` element with the |
| 71 | + same `name` attribute |
| 72 | +5. No matching element was found, Fresh will create a new one and append it to |
| 73 | + `<head>` |
| 74 | + |
| 75 | +> [info]: The `<title>`-tag is automatically deduplicated, even without a `key` |
| 76 | +> prop. |
0 commit comments