Merge commit '5be51ac3db225d5df501ed1fa1499c41d97dbf65'

This commit is contained in:
Bjørn Erik Pedersen
2025-04-10 13:04:51 +02:00
987 changed files with 12379 additions and 14083 deletions

View File

@@ -3,13 +3,11 @@ title: transform.CanHighlight
description: Reports whether the given code language is supported by the Chroma highlighter.
categories: []
keywords: []
action:
aliases: []
related:
- functions/transform/Highlight
- functions/transform/HighlightCodeBlock
returnType: bool
signatures: [transform.CanHighlight LANGUAGE]
params:
functions_and_methods:
aliases: []
returnType: bool
signatures: [transform.CanHighlight LANGUAGE]
---
```go-html-template

View File

@@ -3,11 +3,11 @@ title: transform.Emojify
description: Runs a string through the Emoji emoticons processor.
categories: []
keywords: []
action:
aliases: [emojify]
related: []
returnType: template.HTML
signatures: [transform.Emojify INPUT]
params:
functions_and_methods:
aliases: [emojify]
returnType: template.HTML
signatures: [transform.Emojify INPUT]
aliases: [/functions/emojify]
---
@@ -15,7 +15,7 @@ aliases: [/functions/emojify]
See the list of [emoji shortcodes] for available emoticons.
The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set `enableEmoji` to `true` in your site's [configuration]. Then you can write emoji shorthand directly into your content files;
The `emojify` function can be called in your templates but not directly in your content files by default. For emojis in content files, set [`enableEmoji`] to `true` in your site's configuration. Then you can write emoji shorthand directly into your content files;
```text
I :heart: Hugo!
@@ -23,7 +23,5 @@ I :heart: Hugo!
I :heart: Hugo!
[configuration]: /getting-started/configuration/
[`enableEmoji`]: /configuration/all/#enableemoji
[emoji shortcodes]: /quick-reference/emojis/
[sc]: /templates/shortcode/
[scsource]: https://github.com/gohugoio/hugo/tree/master/docs/layouts/shortcodes

View File

@@ -3,12 +3,11 @@ title: transform.HTMLEscape
description: Returns the given string, escaping special characters by replacing them with HTML entities.
categories: []
keywords: []
action:
aliases: [htmlEscape]
related:
- functions/transform/HTMLUnescape
returnType: string
signatures: [transform.HTMLEscape INPUT]
params:
functions_and_methods:
aliases: [htmlEscape]
returnType: string
signatures: [transform.HTMLEscape INPUT]
aliases: [/functions/htmlescape]
---

View File

@@ -3,12 +3,11 @@ title: transform.HTMLUnescape
description: Returns the given string, replacing each HTML entity with its corresponding character.
categories: []
keywords: []
action:
aliases: [htmlUnescape]
related:
- functions/transform/HTMLEscape
returnType: string
signatures: [transform.HTMLUnescape INPUT]
params:
functions_and_methods:
aliases: [htmlUnescape]
returnType: string
signatures: [transform.HTMLUnescape INPUT]
aliases: [/functions/htmlunescape]
---

View File

@@ -2,22 +2,19 @@
title: transform.Highlight
description: Renders code with a syntax highlighter.
categories: []
keywords: []
action:
aliases: [highlight]
related:
- functions/transform/CanHighlight
- functions/transform/HighlightCodeBlock
returnType: template.HTML
signatures: ['transform.Highlight CODE LANG [OPTIONS]']
keywords: [highlight]
params:
functions_and_methods:
aliases: [highlight]
returnType: template.HTML
signatures: ['transform.Highlight CODE LANG [OPTIONS]']
aliases: [/functions/highlight]
toc: true
---
The `highlight` function uses the [Chroma] syntax highlighter, supporting over 200 languages with more than 40 [available styles].
The `highlight` function uses the [Chroma] syntax highlighter, supporting over 200 languages with more than 40 [highlighting styles].
[chroma]: https://github.com/alecthomas/chroma
[available styles]: https://xyproto.github.io/splash/docs/
[highlighting styles]: /quick-reference/syntax-highlighting-styles/
## Arguments
@@ -30,10 +27,10 @@ LANG
: (`string`) The language of the code to highlight. Choose from one of the [supported languages]. This value is case-insensitive.
OPTIONS
: (`map or string`) A map or space-separate key-value pairs wrapped in quotation marks. Set default values for each option in your [site configuration]. The key names are case-insensitive.
: (`map or string`) A map or comma-separated key-value pairs wrapped in quotation marks. Set default values for each option in your [site configuration]. The key names are case-insensitive.
[site configuration]: /getting-started/configuration-markup#highlight
[supported languages]: /content-management/syntax-highlighting#list-of-chroma-highlighting-languages
[site configuration]: /configuration/markup#highlight
[supported languages]: /content-management/syntax-highlighting#languages
## Examples
@@ -53,4 +50,4 @@ OPTIONS
## Options
{{% include "functions/_common/highlighting-options" %}}
{{% include "_common/syntax-highlighting-options.md" %}}

View File

@@ -3,13 +3,11 @@ title: transform.HighlightCodeBlock
description: Highlights code received in context within a code block render hook.
categories: []
keywords: []
action:
aliases: []
related:
- functions/transform/CanHighlight
- functions/transform/Highlight
returnType: highlight.HighlightResult
signatures: ['transform.HighlightCodeBlock CONTEXT [OPTIONS]']
params:
functions_and_methods:
aliases: []
returnType: highlight.HighlightResult
signatures: ['transform.HighlightCodeBlock CONTEXT [OPTIONS]']
---
This function is only useful within a code block render hook.

View File

@@ -3,13 +3,11 @@ title: transform.Markdownify
description: Renders Markdown to HTML.
categories: []
keywords: []
action:
aliases: [markdownify]
related:
- methods/page/RenderString
- methods/page/RenderShortcodes
returnType: template.HTML
signatures: [transform.Markdownify INPUT]
params:
functions_and_methods:
aliases: [markdownify]
returnType: template.HTML
signatures: [transform.Markdownify INPUT]
aliases: [/functions/markdownify]
---
@@ -21,11 +19,9 @@ If the resulting HTML is a single paragraph, Hugo removes the wrapping `p` tags
To keep the wrapping `p` tags for a single paragraph, use the [`RenderString`] method on the `Page` object, setting the `display` option to `block`.
[`RenderString`]: /methods/page/renderstring/
> [!note]
> Although the `markdownify` function honors [Markdown render hooks] when rendering Markdown to HTML, use the `RenderString` method instead of `markdownify` if a render hook accesses `.Page` context. See issue [#9692] for details.
{{% note %}}
Although the `markdownify` function honors [Markdown render hooks] when rendering Markdown to HTML, use the `RenderString` method instead of `markdownify` if a render hook accesses `.Page` context. See issue [#9692] for details.
[Markdown render hooks]: /render-hooks/
[#9692]: https://github.com/gohugoio/hugo/issues/9692
{{% /note %}}
[`RenderString`]: /methods/page/renderstring/
[Markdown render hooks]: /render-hooks/

View File

@@ -3,11 +3,11 @@ title: transform.Plainify
description: Returns a string with all HTML tags removed.
categories: []
keywords: []
action:
aliases: [plainify]
related: []
returnType: template.HTML
signatures: [transform.Plainify INPUT]
params:
functions_and_methods:
aliases: [plainify]
returnType: template.HTML
signatures: [transform.Plainify INPUT]
aliases: [/functions/plainify]
---

View File

@@ -0,0 +1,213 @@
---
title: transform.PortableText
description: Converts Portable Text to Markdown.
categories: []
keywords: []
params:
functions_and_methods:
returnType: string
signatures: [transform.PortableText MAP]
---
{{< new-in "0.145.0" />}}
[Portable Text](https://www.portabletext.org/) is a JSON structure that represent rich text content in the [Sanity](https://www.sanity.io/) CMS. In Hugo, this function is typically used in a [Content Adapter](https://gohugo.io/content-management/content-adapters/) that creates pages from Sanity data.
## Types supported
- `block` and `span`
- `image`. Note that the image handling is currently very simple; we link to the `asset.url` using `asset.altText` as the image alt text and `asset.title` as the title. For more fine grained control you may want to process the images in a [image render hook](/render-hooks/images/).
- `code` (see the [code-input](https://www.sanity.io/plugins/code-input) plugin). Code will be rendered as [fenced code blocks](/contribute/documentation/#fenced-code-blocks) with any file name provided passed on as a markdown attribute.
> [!note]
> Since the Portable Text gets converted to Markdown before it gets passed to Hugo, rendering of links, headings, images and code blocks can be controlled with [Render Hooks](https://gohugo.io/render-hooks/).
## Example
### Content Adapter
```go-html-template {file="content/_content.gotmpl" copy=true}
{{ $projectID := "mysanityprojectid" }}
{{ $useCached := true }}
{{ $api := "api" }}
{{ if $useCached }}
{{/* See https://www.sanity.io/docs/api-cdn */}}
{{ $api = "apicdn" }}
{{ end }}
{{ $url := printf "https://%s.%s.sanity.io/v2021-06-07/data/query/production" $projectID $api }}
{{/* prettier-ignore-start */ -}}
{{ $q := `*[_type == 'post']{
title, publishedAt, summary, slug, body[]{
...,
_type == "image" => {
...,
asset->{
_id,
path,
url,
altText,
title,
description,
metadata {
dimensions {
aspectRatio,
width,
height
}
}
}
}
},
}`
}}
{{/* prettier-ignore-end */ -}}
{{ $body := dict "query" $q | jsonify }}
{{ $opts := dict "method" "post" "body" $body }}
{{ $r := resources.GetRemote $url $opts }}
{{ $m := $r | transform.Unmarshal }}
{{ $result := $m.result }}
{{ range $result }}
{{ if not .slug }}
{{ continue }}
{{ end }}
{{ $markdown := transform.PortableText .body }}
{{ $content := dict
"mediaType" "text/markdown"
"value" $markdown
}}
{{ $params := dict
"portabletext" (.body | jsonify (dict "indent" " "))
}}
{{ $page := dict
"content" $content
"kind" "page"
"path" .slug.current
"title" .title
"date" (.publishedAt | time )
"summary" .summary
"params" $params
}}
{{ $.AddPage $page }}
{{ end }}
```
### Sanity setup
Below outlines a suitable Sanity studio setup for the above example.
```ts {file="sanity.config.ts" copy=true}
import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
import {visionTool} from '@sanity/vision'
import {schemaTypes} from './schemaTypes'
import {media} from 'sanity-plugin-media'
import {codeInput} from '@sanity/code-input'
export default defineConfig({
name: 'default',
title: 'my-sanity-project',
projectId: 'mysanityprojectid',
dataset: 'production',
plugins: [structureTool(), visionTool(), media(),codeInput()],
schema: {
types: schemaTypes,
},
})
```
Type/schema definition:
```ts {file="schemaTypes/postType.ts" copy=true}
import {defineField, defineType} from 'sanity'
export const postType = defineType({
name: 'post',
title: 'Post',
type: 'document',
fields: [
defineField({
name: 'title',
type: 'string',
validation: (rule) => rule.required(),
}),
defineField({
name: 'summary',
type: 'string',
validation: (rule) => rule.required(),
}),
defineField({
name: 'slug',
type: 'slug',
options: {source: 'title'},
validation: (rule) => rule.required(),
}),
defineField({
name: 'publishedAt',
type: 'datetime',
initialValue: () => new Date().toISOString(),
validation: (rule) => rule.required(),
}),
defineField({
name: 'body',
type: 'array',
of: [
{
type: 'block',
},
{
type: 'image'
},
{
type: 'code',
options: {
language: 'css',
languageAlternatives: [
{title: 'HTML', value: 'html'},
{title: 'CSS', value: 'css'},
],
withFilename: true,
},
},
],
}),
],
})
```
Note that the above requires some additional plugins to be installed:
```bash
npm i sanity-plugin-media @sanity/code-input
```
```ts {file="schemaTypes/index.ts" copy=true}
import {postType} from './postType'
export const schemaTypes = [postType]
```
## Server setup
Unfortunately, Sanity's API does not support [RFC 7234](https://tools.ietf.org/html/rfc7234) and their output changes even if the data has not. A recommended setup is therefore to use their cached `apicdn` endpoint (see above) and then set up a reasonable polling and file cache strategy in your Hugo configuration, e.g:
{{< code-toggle file=hugo >}}
[HTTPCache]
[[HTTPCache.polls]]
disable = false
low = '30s'
high = '3m'
[HTTPCache.polls.for]
includes = ['https://*.*.sanity.io/**']
[caches.getresource]
dir = ':cacheDir/:project'
maxAge = "5m"
{{< /code-toggle >}}
The polling above will be used when running the server/watch mode and rebuild when you push new content in Sanity.
See [Caching in resources.GetRemote](/functions/resources/getremote/#caching) for more fine grained control.

View File

@@ -3,23 +3,20 @@ title: transform.Remarshal
description: Marshals a string of serialized data, or a map, into a string of serialized data in the specified format.
categories: []
keywords: []
action:
aliases: []
related:
- functions/encoding/Jsonify
- functions/transform/Unmarshal
returnType: string
signatures: [transform.Remarshal FORMAT INPUT]
params:
functions_and_methods:
aliases: []
returnType: string
signatures: [transform.Remarshal FORMAT INPUT]
aliases: [/functions/transform.remarshal]
---
The format must be one of `json`, `toml`, `yaml`, or `xml`. If the input is a string of serialized data, it must be valid JSON, TOML, YAML, or XML.
{{% note %}}
This function is primarily a helper for Hugo's documentation, used to convert configuration and front matter examples to JSON, TOML, and YAML.
This is not a general purpose converter, and may change without notice if required for Hugo's documentation site.
{{% /note %}}
> [!note]
> This function is primarily a helper for Hugo's documentation, used to convert configuration and front matter examples to JSON, TOML, and YAML.
>
> This is not a general purpose converter, and may change without notice if required for Hugo's documentation site.
Example 1
: Convert a string of TOML to JSON.

View File

@@ -2,35 +2,27 @@
title: transform.ToMath
description: Renders mathematical equations and expressions written in the LaTeX markup language.
categories: []
keywords: [katex,latex,math,typesetting]
action:
aliases: []
related:
- content-management/mathematics
returnType: types.Result[template.HTML]
signatures: ['transform.ToMath INPUT [OPTIONS]']
keywords: []
params:
functions_and_methods:
aliases: []
returnType: types.Result[template.HTML]
signatures: ['transform.ToMath INPUT [OPTIONS]']
aliases: [/functions/tomath]
toc: true
---
{{< new-in 0.132.0 />}}
Hugo uses an embedded instance of the [KaTeX] display engine to render mathematical markup to HTML. You do not need to install the KaTeX display engine.
[KaTeX]: https://katex.org/
```go-html-template
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
```
{{% note %}}
By default, Hugo renders mathematical markup to [MathML], and does not require any CSS to display the result.
[MathML]: https://developer.mozilla.org/en-US/docs/Web/MathML
To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet.
{{% /note %}}
> [!note]
> By default, Hugo renders mathematical markup to [MathML], and does not require any CSS to display the result.
>
> To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet.
```go-html-template
{{ $opts := dict "output" "htmlAndMathml" }}
@@ -41,18 +33,14 @@ To optimize rendering quality and accessibility, use the `htmlAndMathml` output
Pass a map of options as the second argument to the `transform.ToMath` function. The options below are a subset of the KaTeX [rendering options].
[rendering options]: https://katex.org/docs/options.html
displayMode
: (`bool`) If `true` render in display mode, else render in inline mode. Default is `false`.
: (`bool`) Whether to render in display mode instead of inline mode. Default is `false`.
errorColor
: (`string`) The color of the error messages expressed as an RGB [hexadecimal color]. Default is `#cc0000`.
[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
fleqn
: (`bool`) If `true` render flush left with a 2em left margin. Default is `false`.
: (`bool`) Whether to render flush left with a 2em left margin. Default is `false`.
macros
: (`map`) A map of macros to be used in the math expression. Default is `{}`.
@@ -78,7 +66,7 @@ output
<link href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css" rel="stylesheet">
throwOnError
: (`bool`) If `true` throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTeX. Default is `true`.
: (`bool`) Whether to throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTeX. Default is `true`.
## Error handling
@@ -94,12 +82,10 @@ The example below demonstrates error handing within a template.
Instead of client-side JavaScript rendering of mathematical markup using MathJax or KaTeX, create a passthrough render hook which calls the `transform.ToMath` function.
###### Step 1
### Step 1
Enable and configure the Goldmark [passthrough extension] in your site configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves.
[passthrough extension]: /getting-started/configuration-markup/#passthrough
{{< code-toggle file=hugo copy=true >}}
[markup.goldmark.extensions.passthrough]
enable = true
@@ -109,48 +95,45 @@ block = [['\[', '\]'], ['$$', '$$']]
inline = [['\(', '\)']]
{{< /code-toggle >}}
{{% note %}}
The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration, you will need to double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting.
{{% /note %}}
> [!note]
> The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration, you will need to double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting.
###### Step 2
### Step 2
Create a [passthrough render hook] to capture and render the LaTeX markup.
[passthrough render hook]: /render-hooks/passthrough/
{{< code file=layouts/_default/_markup/render-passthrough.html copy=true >}}
```go-html-template {file="layouts/_default/_markup/render-passthrough.html" copy=true}
{{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }}
{{- with try (transform.ToMath .Inner $opts) }}
{{- with .Err }}
{{ errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }}
{{- errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }}
{{- else }}
{{- .Value }}
{{- $.Page.Store.Set "hasMath" true }}
{{- end }}
{{- end -}}
{{< /code >}}
```
###### Step 3
### Step 3
In your base template, conditionally include the KaTeX CSS within the head element.
{{< code file=layouts/_default/baseof.html copy=true >}}
```go-html-template {file="layouts/_default/baseof.html" copy=true}
<head>
{{ $noop := .WordCount }}
{{ if .Page.Store.Get "hasMath" }}
<link href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css" rel="stylesheet">
{{ end }}
</head>
{{< /code >}}
```
In the above, note the use of a [noop](g) statement to force content rendering before we check the value of `hasMath` with the `Store.Get` method.
#### Step 4
### Step 4
Add some mathematical markup to your content, then test.
{{< code file=content/example.md >}}
```text {file="content/example.md"}
This is an inline \(a^*=x-b^*\) equation.
These are block equations:
@@ -158,4 +141,24 @@ These are block equations:
\[a^*=x-b^*\]
$$a^*=x-b^*$$
{{< /code >}}
```
## Chemistry
{{< new-in 0.144.0 />}}
You can also use the `transform.ToMath` function to render chemical equations, leveraging the `\ce` and `\pu` functions from the [mhchem] package.
```text
$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
```
$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
[KaTeX]: https://katex.org/
[MathML]: https://developer.mozilla.org/en-US/docs/Web/MathML
[mhchem]: https://mhchem.github.io/MathJax-mhchem/
[passthrough extension]: /configuration/markup/#passthrough
[passthrough render hook]: /render-hooks/passthrough/
[rendering options]: https://katex.org/docs/options.html

View File

@@ -3,16 +3,11 @@ title: transform.Unmarshal
description: Parses serialized data and returns a map or an array. Supports CSV, JSON, TOML, YAML, and XML.
categories: []
keywords: []
action:
aliases: [unmarshal]
related:
- functions/transform/Remarshal
- functions/resources/Get
- functions/resources/GetRemote
- functions/encoding/Jsonify
returnType: any
signatures: ['transform.Unmarshal [OPTIONS] INPUT']
toc: true
params:
functions_and_methods:
aliases: [unmarshal]
returnType: any
signatures: ['transform.Unmarshal [OPTIONS] INPUT']
aliases: [/functions/transform.unmarshal]
---
@@ -112,15 +107,12 @@ A remote resource is a file on a remote server, accessible via HTTP or HTTPS.
{{ end }}
```
{{% note %}}
When retrieving remote data, a misconfigured server may send a response header with an incorrect [Content-Type]. For example, the server may set the Content-Type header to `application/octet-stream` instead of `application/json`.
In these cases, pass the resource `Content` through the `transform.Unmarshal` function instead of passing the resource itself. For example, in the above, do this instead:
`{{ $data = .Content | transform.Unmarshal }}`
[Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
{{% /note %}}
> [!note]
> When retrieving remote data, a misconfigured server may send a response header with an incorrect [Content-Type]. For example, the server may set the Content-Type header to `application/octet-stream` instead of `application/json`.
>
> In these cases, pass the resource `Content` through the `transform.Unmarshal` function instead of passing the resource itself. For example, in the above, do this instead:
>
> `{{ $data = .Content | transform.Unmarshal }}`
## Options
@@ -132,8 +124,9 @@ delimiter
comment
: (`string`) The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.
lazyQuotes {{< new-in 0.122.0 />}}
: (`bool`) If true, a quote may appear in an unquoted field and a non-doubled quote may appear in a quoted field. Default is `false`.
lazyQuotes
: {{< new-in 0.122.0 />}}
: (`bool`) Whether to allow a quote in an unquoted field, or to allow a non-doubled quote in a quoted field. Default is `false`.
```go-html-template
{{ $csv := "a;b;c" | transform.Unmarshal (dict "delimiter" ";") }}
@@ -296,4 +289,5 @@ Hugo renders this to:
```
[`index`]: /functions/collections/indexfunction/
[Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
[page bundle]: /content-management/page-bundles/

View File

@@ -3,11 +3,11 @@ title: transform.XMLEscape
description: Returns the given string, removing disallowed characters then escaping the result to its XML equivalent.
categories: []
keywords: []
action:
aliases: []
related: []
returnType: string
signatures: [transform.XMLEscape INPUT]
params:
functions_and_methods:
aliases: []
returnType: string
signatures: [transform.XMLEscape INPUT]
---
{{< new-in 0.121.0 />}}
@@ -31,9 +31,9 @@ For example:
When using `transform.XMLEscape` in a template rendered by Go's [html/template] package, declare the string to be safe HTML to avoid double escaping. For example, in an RSS template:
{{< code file="layouts/_default/rss.xml" >}}
```xml {file="layouts/_default/rss.xml"}
<description>{{ .Summary | transform.XMLEscape | safeHTML }}</description>
{{< /code >}}
```
[disallowed characters]: https://www.w3.org/TR/xml/#charsets
[html entities]: https://developer.mozilla.org/en-us/docs/glossary/entity

View File

@@ -1,12 +1,7 @@
---
title: Transform functions
linkTitle: transform
description: Template functions to transform values from one format to another.
description: Use these functions to transform values from one format to another.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to transform values from one format to another.