Merge commit '8b9803425e63e1b1801f8d5d676e96368d706722'

This commit is contained in:
Bjørn Erik Pedersen
2024-06-21 09:41:24 +02:00
475 changed files with 7408 additions and 4720 deletions

View File

@@ -7,7 +7,7 @@ cascade:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -0,0 +1,14 @@
---
# Do not remove front matter.
---
Hugo uses Go's [text/template] and [html/template] packages.
The text/template package implements data-driven templates for generating textual output, while the html/template package implements data-driven templates for generating HTML output safe against code injection.
By default, Hugo uses the html/template package when rendering HTML files.
To generate HTML output that is safe against code injection, the html/template package escapes strings in certain contexts.
[text/template]: https://pkg.go.dev/text/template
[html/template]: https://pkg.go.dev/html/template

View File

@@ -1,12 +1,12 @@
---
title: Functions
linkTitle: Overview
linkTitle: In this section
description: A list of Hugo template functions including examples.
categories: []
keywords: []
menu:
docs:
identifier: functions-overview
identifier: functions-in-this-section
parent: functions
weight: 10
weight: 10

View File

@@ -65,7 +65,7 @@ You can use `after` in combination with the [`first`] function and Hugo's [power
{{ end }}
{{< /code >}}
[`first`]: /functions/collections/first
[list/section page]: /templates/section-templates
[`first`]: /functions/collections/first/
[list/section page]: /templates/section-templates/
[lists]: /templates/lists/#sort-content
[`slice`]: /functions/collections/slice/

View File

@@ -58,7 +58,7 @@ To list everything except blog articles (`blog`) and frequently asked questions
{{% note %}}
Although the example above demonstrates the `complement` function, you could use the [`where`] function as well:
[`where`]: /functions/collections/where
[`where`]: /functions/collections/where/
{{% /note %}}
```go-html-template

View File

@@ -1,6 +1,6 @@
---
title: collections.Dictionary
description: Creates a map from a list of key and value pairs.
description: Returns a map composed of the given key-value pairs.
categories: []
keywords: []
action:
@@ -8,10 +8,12 @@ action:
related:
- functions/collections/Slice
returnType: mapany
signatures: ['collections.Dictionary KEY VALUE [VALUE...]']
signatures: ['collections.Dictionary [VALUE...]']
aliases: [/functions/dict]
---
Specify the key-value pairs as individual arguments:
```go-html-template
{{ $m := dict "a" 1 "b" 2 }}
```
@@ -25,6 +27,12 @@ The above produces this data structure:
}
```
To create an empty map:
```go-html-template
{{ $m := dict }}
```
Note that the `key` can be either a `string` or a `string slice`. The latter is useful to create a deeply nested structure, e.g.:
@@ -43,26 +51,3 @@ The above produces this data structure:
}
}
```
## Pass values to a partial template
The partial below creates an SVG and expects `fill`, `height` and `width` from the caller:
### Partial definition
{{< code file=layouts/partials/svgs/external-links.svg >}}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
fill="{{ .fill }}" width="{{ .width }}" height="{{ .height }}" viewBox="0 0 32 32" aria-label="External Link">
<path d="M25.152 16.576v5.696q0 2.144-1.504 3.648t-3.648 1.504h-14.848q-2.144 0-3.648-1.504t-1.504-3.648v-14.848q0-2.112 1.504-3.616t3.648-1.536h12.576q0.224 0 0.384 0.16t0.16 0.416v1.152q0 0.256-0.16 0.416t-0.384 0.16h-12.576q-1.184 0-2.016 0.832t-0.864 2.016v14.848q0 1.184 0.864 2.016t2.016 0.864h14.848q1.184 0 2.016-0.864t0.832-2.016v-5.696q0-0.256 0.16-0.416t0.416-0.16h1.152q0.256 0 0.416 0.16t0.16 0.416zM32 1.152v9.12q0 0.48-0.352 0.8t-0.8 0.352-0.8-0.352l-3.136-3.136-11.648 11.648q-0.16 0.192-0.416 0.192t-0.384-0.192l-2.048-2.048q-0.192-0.16-0.192-0.384t0.192-0.416l11.648-11.648-3.136-3.136q-0.352-0.352-0.352-0.8t0.352-0.8 0.8-0.352h9.12q0.48 0 0.8 0.352t0.352 0.8z"></path>
</svg>
{{< /code >}}
### Partial call
The `fill`, `height` and `width` values can be stored in one object with `dict` and passed to the partial:
{{< code file=layouts/_default/list.html >}}
{{ partial "svgs/external-links.svg" (dict "fill" "#01589B" "width" 10 "height" 20 ) }}
{{< /code >}}
[partials]: /templates/partials/

View File

@@ -34,4 +34,4 @@ Use `first` and [`where`] together.
{{ end }}
```
[`where`]: /functions/collections/where
[`where`]: /functions/collections/where/

View File

@@ -1,6 +1,6 @@
---
title: collections.Index
description: Looks up the index(es) or key(s) of the data structure passed into it.
description: Returns the object, element, or value associated with the given key or keys.
categories: []
keywords: []
action:
@@ -8,88 +8,44 @@ action:
related: []
returnType: any
signatures:
- collections.Index COLLECTION INDEXES
- collections.Index COLLECTION KEYS
- collections.Index COLLECTION KEY...
aliases: [/functions/index,/functions/index-function]
---
The `index` functions returns the result of indexing its first argument by the following arguments. Each indexed item must be a map or a slice, e.g.:
Each indexed item must be a map or a slice:
```go-html-template
{{ $slice := slice "a" "b" "c" }}
{{ index $slice 0 }} → a
{{ index $slice 1 }} → b
{{ $s := slice "a" "b" "c" }}
{{ index $s 0 }} → a
{{ index $s 1 }} → b
{{ $map := dict "a" 100 "b" 200 }}
{{ index $map "b" }} → 200
{{ $m := dict "a" 100 "b" 200 }}
{{ index $m "b" }} → 200
```
The function takes multiple indices as arguments, and this can be used to get nested values, e.g.:
Use two or more keys to access a nested value:
```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $map "c" 1 }} → 20
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $map "c" "e" }} → 20
{{ $m := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $m "c" 1 }} → 20
{{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $m "c" "e" }} → 20
```
You may write multiple indices as a slice:
You may also use a slice of keys to access a nested value:
```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $slice := slice "c" "e" }}
{{ index $map $slice }} → 20
{{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $s := slice "c" "e" }}
{{ index $m $s }} → 20
```
## Example: load data from a path based on front matter parameters
Assume you want to add a `location = ""` field to your front matter for every article written in `content/vacations/`. You want to use this field to populate information about the location at the bottom of the article in your `single.html` template. You also have a directory in `data/locations/` that looks like the following:
```text
data/
└── locations/
├── abilene.toml
├── chicago.toml
├── oslo.toml
└── provo.toml
```
Here is an example:
{{< code-toggle file=data/locations/oslo >}}
website = "https://www.oslo.kommune.no"
pop_city = 658390
pop_metro = 1717900
{{< /code-toggle >}}
The example we will use will be an article on Oslo, whose front matter should be set to exactly the same name as the corresponding file name in `data/locations/`:
{{< code-toggle file=content/articles/oslo.md fm=true >}}
title = "My Norwegian Vacation"
location = "oslo"
{{< /code-toggle >}}
The content of `oslo.toml` can be accessed from your template using the following node path: `.Site.Data.locations.oslo`. However, the specific file you need is going to change according to the front matter.
This is where the `index` function is needed. `index` takes 2 arguments in this use case:
1. The node path
2. A string corresponding to the desired data; e.g.&mdash;
Use the `collections.Index` function to access a nested value when the key is variable. For example, these are equivalent:
```go-html-template
{{ index .Site.Data.locations "oslo" }}
```
The variable for `.Params.location` is a string and can therefore replace `oslo` in the example above:
```go-html-template
{{ index .Site.Data.locations .Params.location }}
=> map[website:https://www.oslo.kommune.no pop_city:658390 pop_metro:1717900]
```
Now the call will return the specific file according to the location specified in the content's front matter, but you will likely want to write specific properties to the template. You can do this by continuing down the node path via dot notation (`.`):
```go-html-template
{{ (index .Site.Data.locations .Params.location).pop_city }}
=> 658390
{{ .Site.Params.foo }}
{{ $k := "foo" }}
{{ index .Site.Params $k }}
```

View File

@@ -8,13 +8,13 @@ action:
related:
- methods/pages/Related
returnType: types.KeyValues
signatures: [collections.KeyVals KEY VALUES...]
signatures: [collections.KeyVals KEY VALUE...]
aliases: [/functions/keyvals]
---
The primary application for this function is the definition of the `namedSlices` parameter in the options map passed to the [`Related`] method on the `Pages` object.
The primary application for this function is the definition of the `namedSlices` value in the options map passed to the [`Related`] method on the `Pages` object.
[`Related`]: /methods/pages/related
[`Related`]: /methods/pages/related/
See [related content](/content-management/related).

View File

@@ -15,8 +15,8 @@ action:
The `collections.NewScratch` function creates a locally scoped [scratch pad] to store and manipulate data. To create a scratch pad that is attached to a `Page` object, use the [`Scratch`] or [`Store`] method.
[`Scratch`]: /methods/page/scratch
[`Store`]: /methods/page/store
[`Scratch`]: /methods/page/scratch/
[`Store`]: /methods/page/store/
[scratch pad]: /getting-started/glossary/#scratch-pad
## Methods

View File

@@ -1,6 +1,6 @@
---
title: collections.Querify
description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs.
description: Returns a URL query string composed of the given key-value pairs.
categories: []
keywords: []
action:
@@ -9,24 +9,29 @@ action:
- functions/go-template/urlquery.md
returnType: string
signatures:
- collections.Querify VALUE [VALUE...]
- collections.Querify COLLECTION
- collections.Querify [VALUE...]
aliases: [/functions/querify]
---
`querify` takes a set or slice of key-value pairs and returns a [query string](https://en.wikipedia.org/wiki/Query_string) that can be appended to a URL.
Specify the key-value pairs as individual arguments, or as a slice. The following are equivalent:
The following examples create a link to a search results page on Google.
```go-html-template
<a href="https://www.google.com?{{ (querify "q" "test" "page" 3) | safeURL }}">Search</a>
{{ $qs := slice "q" "test" "page" 3 }}
<a href="https://www.google.com?{{ (querify $qs) | safeURL }}">Search</a>
{{ collections.Querify "a" 1 "b" 2 }}
{{ collections.Querify (slice "a" 1 "b" 2) }}
```
Both of these examples render the following HTML:
To append a query string to a URL:
```go-html-template
{{ $qs := collections.Querify "a" 1 "b" 2 }}
{{ $href := printf "https://example.org?%s" $qs }}
<a href="{{ $href }}">Link</a>
```
Hugo renders this to:
```html
<a href="https://www.google.com?page=3&q=test">Search</a>
<a href="https://example.org?a=1&amp;b=2">Link</a>
```

View File

@@ -1,6 +1,6 @@
---
title: collections.Slice
description: Creates a slice of all passed arguments.
description: Returns a slice composed of the given values.
categories: []
keywords: []
action:
@@ -8,7 +8,7 @@ action:
related:
- functions/collections/Dictionary
returnType: any
signatures: [collections.Slice ITEM...]
signatures: ['collections.Slice [VALUE...]']
aliases: [/functions/slice]
---
@@ -16,3 +16,9 @@ aliases: [/functions/slice]
{{ $s := slice "a" "b" "c" }}
{{ $s }} → [a b c]
```
To create an empty slice:
```go-html-template
{{ $s := slice }}
```

View File

@@ -144,7 +144,7 @@ After sorting:
{{% note %}}
Although you can use the `sort` function to sort a page collection, Hugo provides [sorting and grouping methods] as well.
[sorting and grouping methods]: /methods/pages
[sorting and grouping methods]: /methods/pages/
{{% /note %}}
In this contrived example, sort the site's regular pages by `.Type` in descending order:

View File

@@ -12,7 +12,7 @@ toc: true
aliases: [/functions/where]
---
The `where` function returns the given collection, removing elements that do not satisfy the comparison condition. The comparison condition is comprised of the `KEY`, `OPERATOR`, and `VALUE` arguments:
The `where` function returns the given collection, removing elements that do not satisfy the comparison condition. The comparison condition is composed of the `KEY`, `OPERATOR`, and `VALUE` arguments:
```text
collections.Where COLLECTION KEY [OPERATOR] VALUE
@@ -204,10 +204,10 @@ Use the `like` operator to compare string values. Comparing other data types wil
There are four predefined front matter dates: [`date`], [`publishDate`], [`lastmod`], and [`expiryDate`]. Regardless of the front matter data format (TOML, YAML, or JSON) these are [`time.Time`] values, allowing precise comparisons.
[`date`]: /methods/page/date
[`publishdate`]: /methods/page/publishdate
[`lastmod`]: /methods/page/lastmod
[`expirydate`]: /methods/page/expirydate
[`date`]: /methods/page/date/
[`publishdate`]: /methods/page/publishdate/
[`lastmod`]: /methods/page/lastmod/
[`expirydate`]: /methods/page/expirydate/
[`time.Time`]: https://pkg.go.dev/time#Time
For example, to return a collection of pages that were created before the current year:
@@ -243,7 +243,7 @@ To return a collection of future events:
{{ $futureEvents := where $events "Params.eventDate" "gt" now }}
```
When working with YAML or JSON, or quoted TOML values, custom dates are strings; you cannot compare them with `time.Time` values. String comparisons may be possible if the custom date layout is consistent from one page to the next. However, to be safe, filter the pages by ranging through the collection:
When working with YAML or JSON, or quoted TOML values, custom dates are strings; you cannot compare them with `time.Time` values. String comparisons may be possible if the custom date layout is consistent from one page to the next. To be safe, filter the pages by ranging through the collection:
```go-html-template
{{ $events := where .Site.RegularPages "Type" "events" }}
@@ -288,7 +288,7 @@ These are equivalent:
Useful for theme authors, avoid hardcoding section names by using the `where` function with the [`MainSections`] method on a `Site` object.
[`MainSections`]: /methods/site/mainsections
[`MainSections`]: /methods/site/mainsections/
```go-html-template
{{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }}
@@ -403,7 +403,7 @@ To exclude a page with an undefined field from a boolean _inequality_ test:
2. Create a collection using a nil comparison
3. Subtract the second collection from the first collection using the [`collections.Complement`] function.
[`collections.Complement`]: /functions/collections/complement
[`collections.Complement`]: /functions/collections/complement/
This template:

View File

@@ -21,7 +21,7 @@ When the second argument is the boolean `false` value, the `default` function re
To set a default value based on truthiness, use the [`or`] operator instead.
[`or`]: /functions/go-template/or
[`or`]: /functions/go-template/or/
{{% /note %}}
The `default` function returns the second argument if set:

View File

@@ -25,3 +25,5 @@ aliases: [/functions/eq]
{{ eq 1 2 1 }} → true
{{ eq 1 2 2 }} → false
```
You can also use the `compare.Eq` function to compare strings, boolean values, dates, slices, maps, and pages.

View File

@@ -30,3 +30,11 @@ aliases: [/functions/ge]
{{ ge 2 1 2 }} → true
{{ ge 2 2 1 }} → true
```
Use the `compare.Ge` function to compare other data types as well:
```go-html-template
{{ ge "ab" "a" }} → true
{{ ge time.Now (time.AsTime "1964-12-30") }} → true
{{ ge true false }} → true
```

View File

@@ -30,3 +30,11 @@ aliases: [/functions/gt]
{{ gt 2 1 2 }} → false
{{ gt 2 2 1 }} → false
```
Use the `compare.Gt` function to compare other data types as well:
```go-html-template
{{ gt "ab" "a" }} → true
{{ gt time.Now (time.AsTime "1964-12-30") }} → true
{{ gt true false }} → true
```

View File

@@ -30,3 +30,11 @@ aliases: [/functions/le]
{{ le 2 1 2 }} → false
{{ le 2 2 1 }} → false
```
Use the `compare.Le` function to compare other data types as well:
```go-html-template
{{ le "ab" "a" }} → false
{{ le time.Now (time.AsTime "1964-12-30") }} → false
{{ le true false }} → false
```

View File

@@ -30,3 +30,11 @@ aliases: [/functions/lt]
{{ lt 2 1 2 }} → false
{{ lt 2 2 1 }} → false
```
Use the `compare.Lt` function to compare other data types as well:
```go-html-template
{{ lt "ab" "a" }} → false
{{ lt time.Now (time.AsTime "1964-12-30") }} → false
{{ lt true false }} → false
```

View File

@@ -25,3 +25,5 @@ aliases: [/functions/ne]
{{ ne 1 2 1 }} → false
{{ ne 1 2 2 }} → true
```
You can also use the `compare.Ne` function to compare strings, boolean values, dates, slices, maps, and pages.

View File

@@ -15,6 +15,18 @@ action:
toc: true
---
{{% deprecated-in 0.123.0 %}}
Instead, use [`transform.Unmarshal`] with a [global], [page], or [remote] resource.
See the [remote data example].
[`transform.Unmarshal`]: /functions/transform/unmarshal/
[global]: /getting-started/glossary/#global-resource
[page]: /getting-started/glossary/#page-resource
[remote data example]: /functions/resources/getremote/#remote-data
[remote]: /getting-started/glossary/#remote-resource
{{% /deprecated-in %}}
Given the following directory structure:
```text
@@ -31,7 +43,7 @@ Access the data with either of the following:
```
{{% note %}}
When working with local data, the filepath is relative to the working directory.
When working with local data, the file path is relative to the working directory.
You must not place CSV files in the project's data directory.
{{% /note %}}
@@ -81,7 +93,7 @@ my-project/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $p := "data/pets.csv" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
@@ -105,7 +117,7 @@ my-project/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $p := "pets.csv" }}
{{ with .Resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
@@ -120,7 +132,7 @@ my-project/
Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`] when accessing a remote resource to improve error handling and cache control.
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $u := "https://example.org/pets.csv" }}
{{ with resources.GetRemote $u }}
{{ with .Err }}
@@ -134,7 +146,7 @@ Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`]
{{ end }}
```
[`Resources.Get`]: methods/page/Resources
[`resources.GetRemote`]: /functions/resources/getremote
[`resources.Get`]: /functions/resources/get
[`transform.Unmarshal`]: /functions/transform/unmarshal
[`Resources.Get`]: /methods/page/resources/
[`resources.GetRemote`]: /functions/resources/getremote/
[`resources.Get`]: /functions/resources/get/
[`transform.Unmarshal`]: /functions/transform/unmarshal/

View File

@@ -15,6 +15,18 @@ action:
toc: true
---
{{% deprecated-in 0.123.0 %}}
Instead, use [`transform.Unmarshal`] with a [global], [page], or [remote] resource.
See the [remote data example].
[`transform.Unmarshal`]: /functions/transform/unmarshal/
[global]: /getting-started/glossary/#global-resource
[page]: /getting-started/glossary/#page-resource
[remote data example]: /functions/resources/getremote/#remote-data
[remote]: /getting-started/glossary/#remote-resource
{{% /deprecated-in %}}
Given the following directory structure:
```text
@@ -31,7 +43,7 @@ Access the data with either of the following:
```
{{% note %}}
When working with local data, the filepath is relative to the working directory.
When working with local data, the file path is relative to the working directory.
{{% /note %}}
Access remote data with either of the following:
@@ -86,7 +98,7 @@ my-project/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
{{ $data = . | transform.Unmarshal }}
@@ -109,7 +121,7 @@ my-project/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $p := "books.json" }}
{{ with .Resources.Get $p }}
{{ $data = . | transform.Unmarshal }}
@@ -123,7 +135,7 @@ my-project/
Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`] when accessing a remote resource to improve error handling and cache control.
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $u := "https://example.org/books.json" }}
{{ with resources.GetRemote $u }}
{{ with .Err }}
@@ -136,7 +148,7 @@ Consider using the [`resources.GetRemote`] function with [`transform.Unmarshal`]
{{ end }}
```
[`Resources.Get`]: methods/page/Resources
[`resources.GetRemote`]: /functions/resources/getremote
[`resources.Get`]: /functions/resources/get
[`transform.Unmarshal`]: /functions/transform/unmarshal
[`Resources.Get`]: /methods/page/resources/
[`resources.GetRemote`]: /functions/resources/getremote/
[`resources.Get`]: /functions/resources/get/
[`transform.Unmarshal`]: /functions/transform/unmarshal/

View File

@@ -11,33 +11,22 @@ action:
---
```go-html-template
{{ $data := "" }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
<pre>{{ debug.Dump site.Data.books }}</pre>
```
```go-html-template
<pre>{{ debug.Dump $data }}</pre>
```
```text
[]interface {}{
map[string]interface {}{
```json
[
{
"author": "Victor Hugo",
"rating": 5.0,
"title": "Les Misérables",
"rating": 4,
"title": "The Hunchback of Notre Dame"
},
map[string]interface {}{
{
"author": "Victor Hugo",
"rating": 4.0,
"title": "The Hunchback of Notre Dame",
},
}
"rating": 5,
"title": "Les Misérables"
}
]
```
{{% note %}}

View File

@@ -33,5 +33,5 @@ hugo --logLevel info
The results are displayed in the console at the end of the build. You can have as many timers as you want and if you don't stop them, they will be stopped at the end of build.
```text
INFO timer: name TestSqrt total 12.429355ms
INFO timer: name TestSqrt count 1002 duration 2.496017496s average 2.491035ms median 2.282291ms
```

View File

@@ -11,10 +11,10 @@ action:
toc: true
---
Useful in a code block [render hook], the `diagram.Goat` function converts ASCII art to an SVG diagram, returning a [GoAT] diagram object with the following methods:
Useful in a [code block render hook], the `diagram.Goat` function converts ASCII art to an SVG diagram, returning a [GoAT] diagram object with the following methods:
[GoAT]: https://github.com/blampe/goat#readme
[render hook]: https://gohugo.io/templates/render-hooks/
[code block render hook]: /render-hooks/code-blocks/
Inner
: (`template.HTML`) Returns the SVG child elements without a wrapping `svg` element, allowing you to create your own wrapper.
@@ -30,9 +30,11 @@ Height
## GoAT Diagrams
Hugo natively supports [GoAT] diagrams.
Hugo natively supports [GoAT](https://github.com/bep/goat) diagrams with an [embedded code block render hook].
This markdown:
[embedded code block render hook]: {{% eturl render-codeblock-goat %}}
This Markdown:
````
```goat
@@ -60,9 +62,7 @@ Which appears in your browser as:
'---' '-' '+' '+' '---'
```
To customize rendering, override Hugo's [built-in code block render hook] for GoAT diagrams.
[built-in code block render hook]: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/_default/_markup/render-codeblock-goat.html
To customize rendering, override Hugo's [embedded code block render hook] for GoAT diagrams.
## Code block render hook
@@ -83,7 +83,7 @@ By way of example, let's create a code block render hook to render GoAT diagrams
</figure>
{{< /code >}}
This markdown:
This Markdown:
{{< code file=content/example.md lang=text >}}
```goat {class="foo" caption="Diagram 1: Example"}

View File

@@ -8,6 +8,7 @@ action:
related:
- functions/fmt/Erroridf
- functions/fmt/Warnf
- functions/fmt/Warnidf
returnType: string
signatures: ['fmt.Errorf FORMAT [INPUT]']
aliases: [/functions/errorf]
@@ -18,9 +19,9 @@ aliases: [/functions/errorf]
The `errorf` function evaluates the format string, then prints the result to the ERROR log and fails the build.
```go-html-template
{{ errorf "The %q shortcode requires a src parameter. See %s" .Name .Position }}
{{ errorf "The %q shortcode requires a src argument. See %s" .Name .Position }}
```
Use the [`erroridf`] function to allow optional suppression of specific errors.
[`erroridf`]: /functions/fmt/erroridf
[`erroridf`]: /functions/fmt/erroridf/

View File

@@ -1,6 +1,6 @@
---
title: fmt.Erroridf
description: Log a suppressable ERROR from a template.
description: Log a suppressible ERROR from a template.
categories: []
keywords: []
action:
@@ -8,6 +8,7 @@ action:
related:
- functions/fmt/Errorf
- functions/fmt/Warnf
- functions/fmt/Warnidf
returnType: string
signatures: ['fmt.Erroridf ID FORMAT [INPUT]']
aliases: [/functions/erroridf]
@@ -15,7 +16,7 @@ aliases: [/functions/erroridf]
{{% include "functions/fmt/_common/fmt-layout.md" %}}
The `erroridf` function evaluates the format string, then prints the result to the ERROR log and fails the build. Unlike the [`errorf`] function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreErrors` array in your site configuration.
The `erroridf` function evaluates the format string, then prints the result to the ERROR log and fails the build. Unlike the [`errorf`] function, you may suppress errors logged by the `erroridf` function by adding the message ID to the `ignoreLogs` array in your site configuration.
This template code:
@@ -28,13 +29,13 @@ Produces this console log:
```text
ERROR You should consider fixing this.
You can suppress this error by adding the following to your site configuration:
ignoreErrors = ['error-42']
ignoreLogs = ['error-42']
```
To suppress this message:
{{< code-toggle file=hugo >}}
ignoreErrors = ["error-42"]
ignoreLogs = ["error-42"]
{{< /code-toggle >}}
[`errorf`]: /functions/fmt/errorf
[`errorf`]: /functions/fmt/errorf/

View File

@@ -8,6 +8,7 @@ action:
related:
- functions/fmt/Errorf
- functions/fmt/Erroridf
- functions/fmt/Warnidf
returnType: string
signatures: ['fmt.Warnf FORMAT [INPUT]']
aliases: [/functions/warnf]
@@ -21,6 +22,8 @@ The `warnf` function evaluates the format string, then prints the result to the
{{ warnf "The %q shortcode was unable to find %s. See %s" .Name $file .Position }}
```
Use the [`warnidf`] function to allow optional suppression of specific warnings.
To prevent suppression of duplicate messages when using `warnf` for debugging, make each message unique with the [`math.Counter`] function. For example:
@@ -30,4 +33,6 @@ To prevent suppression of duplicate messages when using `warnf` for debugging, m
{{ end }}
```
[`math.Counter`]: /functions/math/counter
[`math.Counter`]: /functions/math/counter/
[`warnidf`]: /functions/fmt/warnidf/

View File

@@ -0,0 +1,43 @@
---
title: fmt.Warnidf
description: Log a suppressible WARNING from a template.
categories: []
keywords: []
action:
aliases: [warnidf]
related:
- functions/fmt/Errorf
- functions/fmt/Erroridf
- functions/fmt/Warnf
returnType: string
signatures: ['fmt.Warnidf ID FORMAT [INPUT]']
aliases: [/functions/warnidf]
---
{{< new-in 0.123.0 >}}
{{% include "functions/fmt/_common/fmt-layout.md" %}}
The `warnidf` function evaluates the format string, then prints the result to the WARNING log. Unlike the [`warnf`] function, you may suppress warnings logged by the `warnidf` function by adding the message ID to the `ignoreLogs` array in your site configuration.
This template code:
```go-html-template
{{ warnidf "warning-42" "You should consider fixing this." }}
```
Produces this console log:
```text
WARN You should consider fixing this.
You can suppress this warning by adding the following to your site configuration:
ignoreLogs = ['warning-42']
```
To suppress this message:
{{< code-toggle file=hugo >}}
ignoreLogs = ["warning-42"]
{{< /code-toggle >}}
[`warnf`]: /functions/fmt/warnf/

View File

@@ -7,7 +7,7 @@ cascade:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -35,7 +35,7 @@ Do not use the global `page` function in shortcodes, partials called by shortcod
## Explanation
Hugo almost always passes a `Page` as the data context into the top level template (e.g., `single.html`). The one exception is the multihost sitemap template. This means that you can access the current page with the `.` variable in the template.
Hugo almost always passes a `Page` as the data context into the top level template (e.g., `single.html`). The one exception is the multihost sitemap template. This means that you can access the current page with the `.` in the template.
But when you are deeply nested inside of a [content view], [partial], or [render hook], it is not always practical or possible to access the `Page` object.
@@ -101,8 +101,8 @@ When you call the [`Summary`] method, Hugo renders the page content including sh
If Hugo renders the section page before a content page, the cached rendered shortcode will be incorrect. You cannot control the rendering sequence due to concurrency.
[`Summary`]: /methods/page/summary
[`partialCached`]: /functions/partials/includecached
[`Summary`]: /methods/page/summary/
[`partialCached`]: /functions/partials/includecached/
[content view]: /getting-started/glossary/#content-view
[partial]: /getting-started/glossary/#partial
[render hook]: /getting-started/glossary/#render-hook

View File

@@ -12,17 +12,19 @@ action:
aliases: [/functions/site]
---
At the top level of a template that receives the `Site` object in context, these are equivalent:
Use the `site` function to return the `Site` object regardless of current context.
```go-html-template
{{ .Site.Params.foo }}
{{ site.Params.foo }}
```
When the `Site` object is not in context, use the global `site` function:
When the `Site` object is in context you can use the `Site` property:
```go-html-template
{{ site.Params.foo }}
<!-- current context -->
{{ .Site.Params.foo }}
<!-- template context -->
{{ $.Site.Params.foo }}
```
{{% note %}}

View File

@@ -7,7 +7,7 @@ cascade:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -48,8 +48,8 @@ Use with the [`template`] function:
{{ end }}
```
[`block`]: /functions/go-template/block
[`template`]: /functions/go-template/block
[`block`]: /functions/go-template/block/
[`template`]: /functions/go-template/block/
[`partial`]: /functions/partials/include/
{{% include "functions/go-template/_common/text-template.md" %}}

View File

@@ -64,6 +64,6 @@ Use `else if` to check multiple conditions.
{{% include "functions/go-template/_common/text-template.md" %}}
[`if`]: /functions/go-template/if
[`with`]: /functions/go-template/with
[`range`]: /functions/go-template/range
[`if`]: /functions/go-template/if/
[`with`]: /functions/go-template/with/
[`range`]: /functions/go-template/range/

View File

@@ -58,8 +58,8 @@ Use with the [`define`] statement:
{{% include "functions/go-template/_common/text-template.md" %}}
[`block`]: /functions/go-template/block
[`define`]: /functions/go-template/define
[`if`]: /functions/go-template/if
[`range`]: /functions/go-template/range
[`with`]: /functions/go-template/with
[`block`]: /functions/go-template/block/
[`define`]: /functions/go-template/define/
[`if`]: /functions/go-template/if/
[`range`]: /functions/go-template/range/
[`with`]: /functions/go-template/with/

View File

@@ -51,4 +51,4 @@ Use `else if` to check multiple conditions.
{{% include "functions/go-template/_common/text-template.md" %}}
[`else`]: /functions/go-template/else
[`else`]: /functions/go-template/else/

View File

@@ -75,7 +75,7 @@ This template will render the page title three times:
Gaining a thorough understanding of context is critical for anyone writing template code.
{{% /note %}}
[`seq`]: functions/collections/seq/
[`seq`]: /functions/collections/seq/
[context]: /getting-started/glossary/#context
## Array or slice of scalars
@@ -194,6 +194,6 @@ Unlike ranging over an array or slice, Hugo sorts by key when ranging over a map
{{% include "functions/go-template/_common/text-template.md" %}}
[`else`]: /functions/go-template/else
[`break`]: /functions/go-template/break
[`continue`]: /functions/go-template/continue
[`else`]: /functions/go-template/else/
[`break`]: /functions/go-template/break/
[`continue`]: /functions/go-template/continue/

View File

@@ -80,7 +80,7 @@ See additional examples in the [partial templates] section.
## Usage
{{% note %}}
Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks
Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks.
{{% /note %}}
A partial that returns a value must contain only one `return` statement, placed at the end of the template.

View File

@@ -13,7 +13,7 @@ action:
signatures: ['template NAME [CONTEXT]']
---
Use the `template` function to execute [internal templates]. For example:
Use the `template` function to execute [embedded templates]. For example:
```go-html-template
{{ range (.Paginate .Pages).Pages }}
@@ -46,4 +46,4 @@ The example above can be rewritten using an [inline partial] template:
[`partial`]: /functions/partials/include/
[inline partial]: /templates/partials/#inline-partials
[internal templates]: /templates/internal
[embedded templates]: /templates/embedded/

View File

@@ -84,4 +84,4 @@ Gaining a thorough understanding of context is critical for anyone writing templ
{{% include "functions/go-template/_common/text-template.md" %}}
[`else`]: /functions/go-template/else
[`else`]: /functions/go-template/else/

View File

@@ -11,5 +11,5 @@ action:
---
```go-html-template
{{ hugo.Generator }} → <meta name="generator" content="Hugo 0.122.0">
{{ hugo.Generator }} → <meta name="generator" content="Hugo 0.126.0">
```

View File

@@ -0,0 +1,40 @@
---
title: hugo.IsMultihost
description: Reports whether each configured language has a unique base URL.
categories: []
keywords: []
action:
aliases: []
related:
- /functions/hugo/IsMultilingual
returnType: bool
signatures: [hugo.IsMultihost]
---
{{< new-in v0.124.0 >}}
Site configuration:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true
[languages]
[languages.de]
baseURL = 'https://de.example.org/'
languageCode = 'de-DE'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.en]
baseURL = 'https://en.example.org/'
languageCode = 'en-US'
languageName = 'English'
title = 'Project Documentation'
weight = 2
{{< /code-toggle >}}
Template:
```go-html-template
{{ hugo.IsMultihost }} → true
```

View File

@@ -0,0 +1,37 @@
---
title: hugo.IsMultilingual
description: Reports whether there are two or more configured languages.
categories: []
keywords: []
action:
related:
- /functions/hugo/IsMultihost
returnType: bool
signatures: [hugo.IsMultilingual]
---
{{< new-in v0.124.0 >}}
Site configuration:
{{< code-toggle file=hugo >}}
defaultContentLanguage = 'de'
defaultContentLanguageInSubdir = true
[languages]
[languages.de]
languageCode = 'de-DE'
languageName = 'Deutsch'
title = 'Projekt Dokumentation'
weight = 1
[languages.en]
languageCode = 'en-US'
languageName = 'English'
title = 'Project Documentation'
weight = 2
{{< /code-toggle >}}
Template:
```go-html-template
{{ hugo.IsMultilingual }} → true
```

View File

@@ -11,5 +11,5 @@ action:
---
```go-html-template
{{ hugo.Version }} → 0.122.0
{{ hugo.Version }} → 0.126.0
```

View File

@@ -13,3 +13,5 @@ action:
```go-html-template
{{ hugo.WorkingDir }} → /home/user/projects/my-hugo-site
```
{{< new-in 0.112.0 >}}

View File

@@ -27,10 +27,10 @@ Supported image formats include GIF, JPEG, PNG, TIFF, and WebP.
{{% note %}}
This is a legacy function, superseded by the [`Width`] and [`Height`] methods for [global], [page], and [remote] resources. See the [image processing] section for details.
[`Width`]: /methods/resource/width
[`Height`]: /methods/resource/height
[`Width`]: /methods/resource/width/
[`Height`]: /methods/resource/height/
[global]: /getting-started/glossary/#global-resource
[image processing]: /content-management/image-processing
[image processing]: /content-management/image-processing/
[page]: /getting-started/glossary/#page-resource
[remote]: /getting-started/glossary/#remote-resource
{{% /note %}}

View File

@@ -15,6 +15,8 @@ action:
toc: true
---
{{< new-in 0.123.0 >}}
## Options
colors
@@ -29,7 +31,7 @@ serpentine
: (`bool`) Applicable to error diffusion dithering methods, serpentine controls whether the error diffusion matrix is applied in a serpentine manner, meaning that it goes right-to-left every other line. This greatly reduces line-type artifacts. Default is `true`.
strength
: (`float`) The strength at which to apply the dithering matrix, typically a value in the range [0, 1]. A value of `1.0` applies the dithering matrix at 100% strength (no modifification of the dither matrix). The `strength` is inversely proportional to contrast; reducing the strength increases the contrast. Setting `strength` to a value such as `0.8` can be useful to reduce noise in the dithered image. Default is `1.0`.
: (`float`) The strength at which to apply the dithering matrix, typically a value in the range [0, 1]. A value of `1.0` applies the dithering matrix at 100% strength (no modification of the dither matrix). The `strength` is inversely proportional to contrast; reducing the strength increases the contrast. Setting `strength` to a value such as `0.8` can be useful to reduce noise in the dithered image. Default is `1.0`.
## Usage

View File

@@ -40,7 +40,7 @@ To apply two or more filters, executing from left to right:
You can also apply image filters using the [`Filter`] method on a `Resource` object.
[`Filter`]: /methods/resource/filter
[`Filter`]: /methods/resource/filter/
## Example

View File

@@ -32,7 +32,7 @@ Create the filter:
Combine with the [`Colors`] method to create a border with one of the image's most dominant colors:
[`Colors`]: /methods/resource/colors
[`Colors`]: /methods/resource/colors/
```go-html-template
{{ with resources.Get "images/original.jpg" }}

View File

@@ -18,7 +18,7 @@ toc: true
This filter has the same options as the [`Process`] method on a `Resource` object, but using it as a filter may be more effective if you need to apply multiple filters to an image.
[`Process`]: /methods/resource/process
[`Process`]: /methods/resource/process/
The process specification is a space-delimited, case-insensitive list of one or more of the following in any sequence:

View File

@@ -13,11 +13,11 @@ action:
toc: true
---
The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. The sharpen radius is approximately 3 times the sigma value.
The sigma argument is used in a gaussian function and affects the radius of effect. Sigma must be positive. The sharpen radius is approximately 3 times the sigma value.
The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
The amount argument controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
The threshold argument controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
## Usage

View File

@@ -7,7 +7,7 @@ cascade:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -4,7 +4,7 @@
Apply the filter using the [`images.Filter`] function:
[`images.Filter`]: /functions/images/filter
[`images.Filter`]: /functions/images/filter/
```go-html-template
{{ with resources.Get "images/original.jpg" }}
@@ -16,7 +16,7 @@ Apply the filter using the [`images.Filter`] function:
You can also apply the filter using the [`Filter`] method on a `Resource` object:
[`Filter`]: methods/resource/filter
[`Filter`]: /methods/resource/filter/
```go-html-template
{{ with resources.Get "images/original.jpg" }}

View File

@@ -16,5 +16,3 @@ aliases: [/functions/singularize]
```go-html-template
{{ "cats" | singularize }} → cat
```
See also the `.Data.Singular` [taxonomy variable](/variables/taxonomy/) for singularizing taxonomy names.

View File

@@ -115,7 +115,7 @@ JSX {{< new-in 0.124.0 >}}
: (`string`) How to handle/transform JSX syntax. One of: `transform`, `preserve`, `automatic`. Default is `transform`. Notably, the `automatic` transform was introduced in React 17+ and will cause the necessary JSX helper functions to be imported automatically. See https://esbuild.github.io/api/#jsx
JSXImportSource {{< new-in 0.124.0 >}}
: (`string`) Which library to use to automatically import its JSX helper functions from. This only works if `JSX` is set to `automatic`. The specified library needs to be installed through NPM and expose certain exports. See https://esbuild.github.io/api/#jsx-import-source
: (`string`) Which library to use to automatically import its JSX helper functions from. This only works if `JSX` is set to `automatic`. The specified library needs to be installed through npm and expose certain exports. See https://esbuild.github.io/api/#jsx-import-source
The combination of `JSX` and `JSXImportSource` is helpful if you want to use a non-React JSX library like Preact, e.g.:

View File

@@ -31,4 +31,4 @@ For a simpler function that adapts to the current language, see [`lang.FormatNum
{{% include "functions/_common/locales.md" %}}
[`lang.FormatNumber`]: /functions/lang/formatnumber
[`lang.FormatNumber`]: /functions/lang/formatnumber/

View File

@@ -27,8 +27,8 @@ Use this function to:
- Create unique warnings as shown above; the [`warnf`] function suppresses duplicate messages
- Create unique target paths for the `resources.FromString` function where the target path is also the cache key
[`warnf`]: /functions/fmt/warnf
[`resources.FromString`]: /functions/resources/fromstring
[`warnf`]: /functions/fmt/warnf/
[`resources.FromString`]: /functions/resources/fromstring/
{{% note %}}
Due to concurrency, the value returned in a given template for a given page will vary from one build to the next. You cannot use this function to assign a static id to each page.

View File

@@ -32,7 +32,7 @@ getenv = ['^HUGO_', '^CI$', '^USER$', '^HOME$']
Read more about Hugo's [security policy].
[security policy]: /about/security-model/#security-policy
[security policy]: /about/security/#security-policy
## Examples

View File

@@ -17,7 +17,7 @@ aliases: [/functions/partial]
Without a [`return`] statement, the `partial` function returns a string of type `template.HTML`. With a `return` statement, the `partial` function can return any data type.
[`return`]: /functions/go-template/return
[`return`]: /functions/go-template/return/
In this example we have three partial templates:
@@ -48,21 +48,24 @@ The "footer" partial renders the site footer. In this contrived example, the foo
{{ partial "breadcrumbs.html" }}
```
You can pass anything in context: a page, a page collection, a scalar value, a slice, or a map. For example:
You can pass anything in context: a page, a page collection, a scalar value, a slice, or a map. In this example we pass the current page and three scalar values:
```go-html-template
{{ $student := dict
{{ $ctx := dict
"page" .
"name" "John Doe"
"major" "Finance"
"gpa" 4.0
}}
{{ partial "render-student-info.html" $student }}
{{ partial "render-student-info.html" $ctx }}
```
Then, within the partial template:
```go-html-template
<p>{{ .name }} is majoring in {{ .major }}. Their grade point average is {{ .gpa }}.</p>
<p>{{ .name }} is majoring in {{ .major }}.</p>
<p>Their grade point average is {{ .gpa }}.</p>
<p>See <a href="{{ .page.RelPermalink }}">details.</a></p>
```
To return a value from a partial template, it must contain only one `return` statement, placed at the end of the template:
@@ -79,7 +82,7 @@ To return a value from a partial template, it must contain only one `return` sta
See&nbsp;[details][`return`].
[`return`]: /functions/go-template/return
[`return`]: /functions/go-template/return/
[breadcrumb navigation]: /content-management/sections/#ancestors-and-descendants
[details]: /functions/go-template/return
[details]: /functions/go-template/return/

View File

@@ -62,4 +62,4 @@ To return a value from a partial template, it must contain only one `return` sta
See&nbsp;[details][`return`].
[`return`]: /functions/go-template/return
[`return`]: /functions/go-template/return/

View File

@@ -28,7 +28,7 @@ This function operates on global resources. A global resource is a file within t
For page resources, use the [`Resources.ByType`] method on the Page object.
[`Resources.ByType`]: /methods/page/resources
[`Resources.ByType`]: /methods/page/resources/
{{% /note %}}
[media type]: https://en.wikipedia.org/wiki/Media_type

View File

@@ -15,9 +15,9 @@ The `resources.Concat` function returns a concatenated slice of resources, cachi
Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods.
[media type]: https://en.wikipedia.org/wiki/Media_type
[`publish`]: /methods/resource/publish
[`permalink`]: /methods/resource/permalink
[`relpermalink`]: /methods/resource/relpermalink
[`publish`]: /methods/resource/publish/
[`permalink`]: /methods/resource/permalink/
[`relpermalink`]: /methods/resource/relpermalink/
```go-html-template
{{ $plugins := resources.Get "js/plugins.js" }}

View File

@@ -25,8 +25,6 @@ The relative URL of the new published resource will be:
/img/new-image-name.jpg
```
The target path must be different than the source path, as shown in the example above.
{{% note %}}
Use the `resources.Copy` function with global, page, and remote resources.
{{% /note %}}

View File

@@ -15,9 +15,9 @@ The `resources.ExecuteAsTemplate` function returns a resource created from a Go
Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods.
[`publish`]: /methods/resource/publish
[`permalink`]: /methods/resource/permalink
[`relpermalink`]: /methods/resource/relpermalink
[`publish`]: /methods/resource/publish/
[`permalink`]: /methods/resource/permalink/
[`relpermalink`]: /methods/resource/relpermalink/
Let's say you have a CSS file that you wish to populate with values from your site configuration:

View File

@@ -15,17 +15,17 @@ The `resources.FromString` function returns a resource created from a string, ca
Hugo publishes the resource to the target path when you call its [`Publish`], [`Permalink`], or [`RelPermalink`] methods.
[`publish`]: /methods/resource/publish
[`permalink`]: /methods/resource/permalink
[`relpermalink`]: /methods/resource/relpermalink
[`publish`]: /methods/resource/publish/
[`permalink`]: /methods/resource/permalink/
[`relpermalink`]: /methods/resource/relpermalink/
Let's say you need to publish a file named "site.json" in the root of your public directory, containing the build date, the Hugo version used to build the site, and the date that the content was last modified. For example:
```json
{
"build_date": "2023-10-03T10:50:40-07:00",
"hugo_version": "0.122.0",
"last_modified": "2023-10-02T15:21:27-07:00"
"build_date": "2024-02-19T12:27:05-08:00",
"hugo_version": "0.126.0",
"last_modified": "2024-02-19T12:01:42-08:00"
}
```
@@ -37,7 +37,7 @@ Place this in your baseof.html template:
{{ $m := dict
"hugo_version" hugo.Version
"build_date" (now.Format $rfc3339)
"last_modified" (site.LastChange.Format $rfc3339)
"last_modified" (site.Lastmod.Format $rfc3339)
}}
{{ $json := jsonify $m }}
{{ $r := resources.FromString "site.json" $json }}
@@ -47,7 +47,7 @@ Place this in your baseof.html template:
The example above:
1. Creates a map with the relevant key/value pairs using the [`dict`] function
1. Creates a map with the relevant key-value pairs using the [`dict`] function
2. Encodes the map as a JSON string using the [`jsonify`] function
3. Creates a resource from the JSON string using the `resources.FromString` function
4. Publishes the file to the root of the public directory using the resource's `.Publish` method
@@ -61,7 +61,7 @@ Combine `resources.FromString` with [`resources.ExecuteAsTemplate`] if your stri
{{ $m := dict
"hugo_version" hugo.Version
"build_date" (now.Format $rfc3339)
"last_modified" (site.LastChange.Format $rfc3339)
"last_modified" (site.Lastmod.Format $rfc3339)
}}
{{ $json := jsonify $m }}
`
@@ -72,6 +72,6 @@ Combine `resources.FromString` with [`resources.ExecuteAsTemplate`] if your stri
{{ end }}
```
[`dict`]: /functions/collections/dictionary
[`jsonify`]: /functions/encoding/jsonify
[`resources.ExecuteAsTemplate`]: /functions/resources/executeastemplate
[`dict`]: /functions/collections/dictionary/
[`jsonify`]: /functions/encoding/jsonify/
[`resources.ExecuteAsTemplate`]: /functions/resources/executeastemplate/

View File

@@ -26,5 +26,5 @@ This function operates on global resources. A global resource is a file within t
For page resources, use the [`Resources.Get`] method on the Page object.
[`Resources.Get`]: /methods/page/resources
[`Resources.Get`]: /methods/page/resources/
{{% /note %}}

View File

@@ -26,7 +26,7 @@ This function operates on global resources. A global resource is a file within t
For page resources, use the [`Resources.GetMatch`] method on the Page object.
[`Resources.GetMatch`]: /methods/page/resources
[`Resources.GetMatch`]: /methods/page/resources/
{{% /note %}}
Hugo determines a match using a case-insensitive [glob pattern].

View File

@@ -69,11 +69,11 @@ You can also change the request method and set the request body:
When retrieving remote data, use the [`transform.Unmarshal`] function to [unmarshal] the response.
[`transform.Unmarshal`]: /functions/transform/unmarshal
[`transform.Unmarshal`]: /functions/transform/unmarshal/
[unmarshal]: /getting-started/glossary/#unmarshal
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $url := "https://example.org/books.json" }}
{{ with resources.GetRemote $url }}
{{ with .Err }}
@@ -86,11 +86,21 @@ When retrieving remote data, use the [`transform.Unmarshal`] function to [unmars
{{ 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 %}}
## Error handling
The [`Err`] method on a resource returned by the `resources.GetRemote` function returns an error message if the HTTP request fails, else nil. If you do not handle the error yourself, Hugo will fail the build.
[`Err`]: /methods/resource/err
[`Err`]: /methods/resource/err/
```go-html-template
{{ $url := "https://broken-example.org/images/a.jpg" }}
@@ -124,7 +134,7 @@ To log an error as a warning instead of an error:
The [`Data`] method on a resource returned by the `resources.GetRemote` function returns information from the HTTP response.
[`Data`]: /methods/resource/data
[`Data`]: /methods/resource/data/
```go-html-template
{{ $url := "https://example.org/images/a.jpg" }}
@@ -194,22 +204,15 @@ For example, you will see the error above if you attempt to download an executab
Although the allowlist contains entries for common media types, you may encounter situations where Hugo is unable to resolve the media type of a file that you know to be safe. In these situations, edit your site configuration to add the media type to the allowlist. For example:
```text
{{< code-toggle file=hugo >}}
[security.http]
mediaTypes=['application/vnd\.api\+json']
```
mediaTypes = ['^image/avif$','^application/vnd\.api\+json$']
{{< /code-toggle >}}
Note that the entry above is:
- An _addition_ to the allowlist; it does not _replace_ the allowlist
- An array of regular expressions
For example, to add two entries to the allowlist:
```text
[security.http]
mediaTypes=['application/vnd\.api\+json','image/avif']
```
[allowlist]: https://en.wikipedia.org/wiki/Whitelist
[Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

View File

@@ -26,7 +26,7 @@ This function operates on global resources. A global resource is a file within t
For page resources, use the [`Resources.Match`] method on the Page object.
[`Resources.Match`]: /methods/page/resources
[`Resources.Match`]: /methods/page/resources/
{{% /note %}}
Hugo determines a match using a case-insensitive [glob pattern].

View File

@@ -46,7 +46,7 @@ targetPath
: (`string`) If not set, the transformed resource's target path will be the original path of the asset file with its extension replaced by `.css`.
vars
: (`map`) A map of key/value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/).
: (`map`) A map of key-value pairs that will be available in the `hugo:vars` namespace. Useful for [initializing Sass variables from Hugo templates](https://discourse.gohugo.io/t/42053/).
```scss
// LibSass
@@ -139,8 +139,8 @@ To install Dart Sass for your builds on GitLab Pages, the `.gitlab-ci.yml` file
```yaml
variables:
HUGO_VERSION: 0.122.0
DART_SASS_VERSION: 1.70.0
HUGO_VERSION: 0.126.0
DART_SASS_VERSION: 1.77.1
GIT_DEPTH: 0
GIT_STRATEGY: clone
GIT_SUBMODULE_STRATEGY: recursive
@@ -173,8 +173,8 @@ To install Dart Sass for your builds on Netlify, the `netlify.toml` file should
```toml
[build.environment]
HUGO_VERSION = "0.122.0"
DART_SASS_VERSION = "1.70.0"
HUGO_VERSION = "0.126.0"
DART_SASS_VERSION = "1.77.1"
TZ = "America/Los_Angeles"
[build]

View File

@@ -6,7 +6,7 @@ _build:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -1,6 +1,6 @@
---
title: safe.CSS
description: Declares the given string as safe CSS string.
description: Declares the given string as a safe CSS string.
categories: []
keywords: []
action:
@@ -13,21 +13,57 @@ action:
- functions/safe/URL
returnType: template.CSS
signatures: [safe.CSS INPUT]
toc: true
aliases: [/functions/safecss]
---
In this context, *safe* means CSS content that matches any of the following:
## Introduction
{{% include "functions/_common/go-html-template-package.md" %}}
## Usage
Use the `safe.CSS` function to encapsulate known safe content that matches any of:
1. The CSS3 stylesheet production, such as `p { color: purple }`.
2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
3. CSS3 declaration productions, such as `color: red; margin: 2px`.
4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
Example: Given `style = "color: red;"` defined in the front matter of your `.md` file:
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
* `<p style="{{ .Params.style | safeCSS }}">…</p>` &rarr; `<p style="color: red;">…</p>`
* `<p style="{{ .Params.style }}">…</p>` &rarr; `<p style="ZgotmplZ">…</p>`
See the [Go documentation] for details.
[Go documentation]: https://pkg.go.dev/html/template#CSS
## Example
Without a safe declaration:
```go-html-template
{{ $style := "color: red;" }}
<p style="{{ $style }}">foo</p>
```
Hugo renders the above to:
```html
<p style="ZgotmplZ">foo</p>
```
{{% note %}}
`ZgotmplZ` is a special value that indicates that unsafe content reached a CSS or URL context.
`ZgotmplZ` is a special value that indicates that unsafe content reached a CSS or URL context at runtime.
{{% /note %}}
To declare the string as safe:
```go-html-template
{{ $style := "color: red;" }}
<p style="{{ $style | safeCSS }}">foo</p>
```
Hugo renders the above to:
```html
<p style="color: red;">foo</p>
```

View File

@@ -13,27 +13,48 @@ action:
- functions/safe/URL
returnType: template.HTML
signatures: [safe.HTML INPUT]
toc: true
aliases: [/functions/safehtml]
---
It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.
## Introduction
Given a site-wide [`hugo.toml`][config] with the following `copyright` value:
{{% include "functions/_common/go-html-template-package.md" %}}
{{< code-toggle file=hugo >}}
copyright = "© 2015 Jane Doe. <a href=\"https://creativecommons.org/licenses/by/4.0/\">Some rights reserved</a>."
{{< /code-toggle >}}
## Usage
`{{ .Site.Copyright | safeHTML }}` in a template would then output:
Use the `safe.HTML` function to encapsulate a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.
```html
© 2015 Jane Doe. <a href="https://creativecommons.org/licenses/by/4.0/">Some rights reserved</a>.
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
See the [Go documentation] for details.
[Go documentation]: https://pkg.go.dev/html/template#HTML
## Example
Without a safe declaration:
```go-html-template
{{ $html := "<em>emphasized</em>" }}
{{ $html }}
```
However, without the `safeHTML` function, html/template assumes `.Site.Copyright` to be unsafe and therefore escapes all HTML tags and renders the whole string as plain text:
Hugo renders the above to:
```html
<p>© 2015 Jane Doe. &lt;a href=&#34;https://creativecommons.org/licenses by/4.0/&#34;&gt;Some rights reserved&lt;/a&gt;.</p>
&lt;em&gt;emphasized&lt;/em&gt;
```
[config]: /getting-started/configuration/
To declare the string as safe:
```go-html-template
{{ $html := "<em>emphasized</em>" }}
{{ $html | safeHTML }}
```
Hugo renders the above to:
```html
<em>emphasized</em>
```

View File

@@ -1,6 +1,6 @@
---
title: safe.HTMLAttr
description: Declares the given key/value pair as a safe HTML attribute.
description: Declares the given key-value pair as a safe HTML attribute.
categories: []
keywords: []
action:
@@ -13,43 +13,54 @@ action:
- functions/safe/URL
returnType: template.HTMLAttr
signatures: [safe.HTMLAttr INPUT]
toc: true
aliases: [/functions/safehtmlattr]
---
Given a site configuration that contains this menu entry:
## Introduction
{{< code-toggle file=hugo >}}
[[menus.main]]
name = "IRC"
url = "irc://irc.freenode.net/#golang"
{{< /code-toggle >}}
{{% include "functions/_common/go-html-template-package.md" %}}
Attempting to use the `url` value directly in an attribute:
## Usage
Use the `safe.HTMLAttr` function to encapsulate an HTML attribute from a trusted source.
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
See the [Go documentation] for details.
[Go documentation]: https://pkg.go.dev/html/template#HTMLAttr
## Example
Without a safe declaration:
```go-html-template
{{ range site.Menus.main }}
<a href="{{ .URL }}">{{ .Name }}</a>
{{ with .Date }}
{{ $humanDate := time.Format "2 Jan 2006" . }}
{{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }}
<time datetime="{{ $machineDate }}">{{ $humanDate }}</time>
{{ end }}
```
Will produce:
Hugo renders the above to:
```html
<a href="#ZgotmplZ">IRC</a>
<time datetime="2024-05-26T07:19:55&#43;02:00">26 May 2024</time>
```
`ZgotmplZ` is a special value, inserted by Go's [template/html] package, that indicates that unsafe content reached a CSS or URL context.
To indicate that the HTML attribute is safe:
To declare the key-value pair as safe:
```go-html-template
{{ range site.Menus.main }}
<a {{ printf "href=%q" .URL | safeHTMLAttr }}>{{ .Name }}</a>
{{ with .Date }}
{{ $humanDate := time.Format "2 Jan 2006" . }}
{{ $machineDate := time.Format "2006-01-02T15:04:05-07:00" . }}
<time {{ printf "datetime=%q" $machineDate | safeHTMLAttr }}>{{ $humanDate }}</time>
{{ end }}
```
{{% note %}}
As demonstrated above, you must pass the HTML attribute name _and_ value through the function. Applying `safeHTMLAttr` to the attribute value has no effect.
{{% /note %}}
Hugo renders the above to:
[template/html]: https://pkg.go.dev/html/template
```html
<time datetime="2024-05-26T07:19:55+02:00">26 May 2024</time>
```

View File

@@ -13,14 +13,54 @@ action:
- functions/safe/URL
returnType: template.JS
signatures: [safe.JS INPUT]
toc: true
aliases: [/functions/safejs]
---
In this context, *safe* means the string encapsulates a known safe EcmaScript5 Expression (e.g., `(x + y * z())`).
## Introduction
Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like `{ foo:bar() }\n['foo']()`, which is both a valid expression and a valid program with a very different meaning.
{{% include "functions/_common/go-html-template-package.md" %}}
Example: Given `hash = "619c16f"` defined in the front matter of your `.md` file:
## Usage
* `<script>var form_{{ .Params.hash | safeJS }};…</script>` &rarr; `<script>var form_619c16f;…</script>`
* `<script>var form_{{ .Params.hash }};…</script>` &rarr; `<script>var form_"619c16f";…</script>`
Use the `safe.JS` function to encapsulate a known safe EcmaScript5 Expression.
Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like `{ foo: bar() }\n['foo']()`, which is both a valid Expression and a valid Program with a very different meaning.
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
Using the `safe.JS` function to include valid but untrusted JSON is not safe. A safe alternative is to parse the JSON with the [`transform.Unmarshal`] function and then pass the resultant object into the template, where it will be converted to sanitized JSON when presented in a JavaScript context.
[`transform.Unmarshal`]: /functions/transform/unmarshal/
See the [Go documentation] for details.
[Go documentation]: https://pkg.go.dev/html/template#JS
## Example
Without a safe declaration:
```go-html-template
{{ $js := "x + y" }}
<script>const a = {{ $js }}</script>
```
Hugo renders the above to:
```html
<script>const a = "x + y"</script>
```
To declare the string as safe:
```go-html-template
{{ $js := "x + y" }}
<script>const a = {{ $js | safeJS }}</script>
```
Hugo renders the above to:
```html
<script>const a = x + y</script>
```

View File

@@ -13,12 +13,27 @@ action:
- functions/safe/URL
returnType: template.JSStr
signatures: [safe.JSStr INPUT]
toc: true
aliases: [/functions/safejsstr]
---
Encapsulates a sequence of characters meant to be embedded between quotes in a JavaScript expression. Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
Without declaring a variable to be a safe JavaScript string:
## Introduction
{{% include "functions/_common/go-html-template-package.md" %}}
## Usage
Use the `safe.JSStr` function to encapsulate a sequence of characters meant to be embedded between quotes in a JavaScript expression.
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
See the [Go documentation] for details.
[Go documentation]: https://pkg.go.dev/html/template#JSStr
## Example
Without a safe declaration:
```go-html-template
{{ $title := "Lilo & Stitch" }}
@@ -27,7 +42,7 @@ Without declaring a variable to be a safe JavaScript string:
</script>
```
Rendered:
Hugo renders the above to:
```html
<script>
@@ -35,7 +50,7 @@ Rendered:
</script>
```
To avoid escaping by Go's [html/template] package:
To declare the string as safe:
```go-html-template
{{ $title := "Lilo & Stitch" }}
@@ -44,12 +59,10 @@ To avoid escaping by Go's [html/template] package:
</script>
```
Rendered:
Hugo renders the above to:
```html
<script>
const a = "Title: " + "Lilo & Stitch";
</script>
```
[html/template]: https://pkg.go.dev/html/template

View File

@@ -13,58 +13,56 @@ action:
- functions/safe/JSStr
returnType: template.URL
signatures: [safe.URL INPUT]
toc: true
aliases: [/functions/safeurl]
---
`safeURL` declares the provided string as a "safe" URL or URL substring (see [RFC 3986]). A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()` from a trusted source should go in the page, but by default dynamic `javascript:` URLs are filtered out since they are a frequently exploited injection vector.
## Introduction
Without `safeURL`, only the URI schemes `http:`, `https:` and `mailto:` are considered safe by Go templates. If any other URI schemes (e.g., `irc:` and `javascript:`) are detected, the whole URL will be replaced with `#ZgotmplZ`. This is to "defang" any potential attack in the URL by rendering it useless.
{{% include "functions/_common/go-html-template-package.md" %}}
The following examples use a [site `hugo.toml`][configuration] with the following [menu entry][menus]:
## Usage
{{< code-toggle file=hugo >}}
[[menus.main]]
name = "IRC: #golang at freenode"
url = "irc://irc.freenode.net/#golang"
{{< /code-toggle >}}
Use the `safe.URL` function to encapsulate a known safe URL or URL substring. Schemes other than the following are considered unsafe:
The following is an example of a sidebar partial that may be used in conjunction with the preceding front matter example:
- `http:`
- `https:`
- `mailto:`
{{< code file=layouts/partials/bad-url-sidebar-menu.html >}}
<!-- This unordered list may be part of a sidebar menu -->
<ul>
{{ range .Site.Menus.main }}
<li><a href="{{ .URL }}">{{ .Name }}</a></li>
{{ end }}
</ul>
{{< /code >}}
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
This partial would produce the following HTML output:
See the [Go documentation] for details.
```html
<!-- This unordered list may be part of a sidebar menu -->
<ul>
<li><a href="#ZgotmplZ">IRC: #golang at freenode</a></li>
</ul>
[Go documentation]: https://pkg.go.dev/html/template#URL
## Example
Without a safe declaration:
```go-html-template
{{ $href := "irc://irc.freenode.net/#golang" }}
<a href="{{ $href }}">IRC</a>
```
The odd output can be remedied by adding ` | safeURL` to our `.URL` page variable:
{{< code file=layouts/partials/correct-url-sidebar-menu.html >}}
<!-- This unordered list may be part of a sidebar menu -->
<ul>
<li><a href="{{ .URL | safeURL }}">{{ .Name }}</a></li>
</ul>
{{< /code >}}
With the `.URL` page variable piped through `safeURL`, we get the desired output:
Hugo renders the above to:
```html
<ul class="sidebar-menu">
<li><a href="irc://irc.freenode.net/#golang">IRC: #golang at freenode</a></li>
</ul>
<a href="#ZgotmplZ">IRC</a>
```
[configuration]: /getting-started/configuration/
[menus]: /content-management/menus/
[RFC 3986]: https://tools.ietf.org/html/rfc3986
{{% note %}}
`ZgotmplZ` is a special value that indicates that unsafe content reached a CSS or URL context at runtime.
{{% /note %}}
To declare the string as safe:
```go-html-template
{{ $href := "irc://irc.freenode.net/#golang" }}
<a href="{{ $href | safeURL }}">IRC</a>
```
Hugo renders the above to:
```html
<a href="irc://irc.freenode.net/#golang">IRC</a>
```

View File

@@ -1,6 +1,6 @@
---
title: strings.ContainsNonSpace
description: Reports whether the given string contains any non-space characters as defined by Unicodes White Space property.
description: Reports whether the given string contains any non-space characters as defined by Unicode's White Space property.
categories: []
keywords: []
action:
@@ -24,7 +24,7 @@ aliases: [/functions/strings.containsnonspace]
{{ strings.ContainsNonSpace "\n abc" }} → true
```
Common white space characters include:
Common whitespace characters include:
```text
'\t', '\n', '\v', '\f', '\r', ' '

View File

@@ -21,4 +21,4 @@ In contrast with the [`strings.RuneCount`] function, which counts every rune in
{{ "Hello, 世界" | strings.CountRunes }} → 8
```
[`strings.RuneCount`]: /functions/strings/runecount
[`strings.RuneCount`]: /functions/strings/runecount/

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

View File

@@ -0,0 +1,33 @@
---
title: strings.Diff
description: Returns an anchored diff of the two texts OLD and NEW in the unified diff format. If OLD and NEW are identical, returns an empty string.
categories: []
keywords: []
action:
related: []
returnType: string
signatures: [strings.Diff OLDNAME OLD NEWNAME NEW]
---
{{< new-in 0.125.0 >}}
Use `strings.Diff` to compare two strings and render a highlighted diff:
```go-html-template
{{ $want := `
<p>The product of 6 and 7 is 42.</p>
<p>The product of 7 and 6 is 42.</p>
`}}
{{ $got := `
<p>The product of 6 and 7 is 42.</p>
<p>The product of 7 and 6 is 13.</p>
`}}
{{ $diff := strings.Diff "want" $want "got" $got }}
{{ transform.Highlight $diff "diff" }}
```
Rendered:
![sreen capture](diff-screen-capture.png)

View File

@@ -30,7 +30,7 @@ By default, `findRESubmatch` finds all matches. You can limit the number of matc
## Practical example
This markdown:
This Markdown:
```text
- [Example](https://example.org)

View File

@@ -21,4 +21,4 @@ In contrast with the [`strings.CountRunes`] function, which excludes whitespace,
{{ "Hello, 世界" | strings.RuneCount }} → 9
```
[`strings.CountRunes`]: /functions/strings/countrunes
[`strings.CountRunes`]: /functions/strings/countrunes/

View File

@@ -1,20 +1,26 @@
---
title: strings.SliceString
description: Creates a slice of a half-open range, including start and end indices.
description: Returns a substring of the given string, beginning with the start position and ending before the end position.
categories: []
keywords: []
action:
aliases: [slicestr]
related: []
related:
- functions/strings/Substr
returnType: string
signatures: ['strings.SliceString STRING START [END]']
signatures: ['strings.SliceString STRING [START] [END]']
aliases: [/functions/slicestr]
---
For example, 1 and 4 creates a slice including elements 1 through&nbsp;3.
The `end` index can be omitted; it defaults to the string's length.
The START and END positions are zero-based, where `0` represents the first character of the string. If START is not specified, the substring will begin at position `0`. If END is not specified, the substring will end after the last character.
```go-html-template
{{ slicestr "BatMan" 3 }}`Man
{{ slicestr "BatMan" 0 3 }}`Bat
{{ slicestr "BatMan" }} → BatMan
{{ slicestr "BatMan" 3 }} → Man
{{ slicestr "BatMan" 0 3 }} → Bat
```
The START and END arguments represent the endpoints of a [half-open interval], a concept that may be difficult to grasp when first encountered. You may find that the [`strings.Substr`] function is easier to understand.
[half-open interval]: /getting-started/glossary/#interval
[`strings.Substr`]: /functions/strings/substr/

View File

@@ -22,5 +22,5 @@ Examples:
{{% note %}}
The `strings.Split` function essentially does the opposite of the [`collections.Delimit`] function. While `split` creates a slice from a string, `delimit` creates a string from a slice.
[`collections.Delimit`]: /functions/collections/delimit
[`collections.Delimit`]: /functions/collections/delimit/
{{% /note %}}

View File

@@ -1,21 +1,20 @@
---
title: strings.Substr
description: Extracts parts of a string from a specified character's position and returns the specified number of characters.
description: Returns a substring of the given string, beginning with the start position and ending after the given length.
categories: []
keywords: []
action:
aliases: [substr]
related: []
related:
- functions/strings/SliceString
returnType: string
signatures: ['strings.Substr STRING START [LENGTH]']
signatures: ['strings.Substr STRING [START] [LENGTH]']
aliases: [/functions/substr]
---
It normally takes two argument: `start` and `length`. It can also take one argument: `start`, i.e. `length` is omitted, in which case the substring starting from start until the end of the string will be returned.
The start position is zero-based, where `0` represents the first character of the string. If START is not specified, the substring will begin at position `0`. Specify a negative START position to extract characters from the end of the string.
To extract characters from the end of the string, use a negative start number.
If `length` is given and is negative, that number of characters will be omitted from the end of string.
If LENGTH is not specified, the substring will include all characters from the START position to the end of the string. If negative, that number of characters will be omitted from the end of string.
```go-html-template
{{ substr "abcdef" 0 }} → abcdef

View File

@@ -32,7 +32,7 @@ To remove leading and trailing newline characters and carriage returns:
The `strings.Trim` function is commonly used in shortcodes to remove leading and trailing newlines characters and carriage returns from the content within the opening and closing shortcode tags.
For example, with this markdown:
For example, with this Markdown:
```text
{{</* my-shortcode */>}}

View File

@@ -20,5 +20,5 @@ Since Go templates are HTML-aware, `truncate` will intelligently handle normal s
{{% note %}}
If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the [`safeHTML`]function before sending the value to `truncate`. Otherwise, the HTML tags will be escaped when passed through the `truncate` function.
[`safeHTML`]: /functions/safe/html
[`safeHTML`]: /functions/safe/html/
{{% /note %}}

View File

@@ -43,4 +43,4 @@ microseconds|`microsecond`, `us`, `µs`
nanoseconds|`nanosecond`, `ns`
[`time.Duration`]: https://pkg.go.dev/time#Duration
[methods]: /methods/duration
[methods]: /methods/duration/

View File

@@ -43,6 +43,6 @@ The `time.Now` function returns a `time.Time` value, so you can chain any of the
{{ time.Now.Unix }} → 1697400955 (int64)
```
[`time.Format`]: /functions/time/format
[`time.Format`]: /functions/time/format/
[localize]: /getting-started/glossary/#localization
[time methods]: /methods/time/

View File

@@ -34,4 +34,4 @@ There are 86400 seconds in one day.
```
[`time.Duration`]: https://pkg.go.dev/time#Duration
[methods]: /methods/duration
[methods]: /methods/duration/

View File

@@ -7,7 +7,7 @@ cascade:
---
<!--
Files within this headless branch bundle are markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Files within this headless branch bundle are Markdown snippets. Each file must contain front matter delimiters, though front matter fields are not required.
Include the rendered content using the "include" shortcode.
-->

View File

@@ -25,6 +25,6 @@ In most contexts Go's [html/template] package will escape special characters. To
{{ htmlUnescape "Lilo &amp; Stitch" | safeHTML }}
```
[`safehtml`]: /functions/safe/html
[`safehtml`]: /functions/safe/html/
[html entities]: https://developer.mozilla.org/en-us/docs/glossary/entity
[html/template]: https://pkg.go.dev/html/template

View File

@@ -1,6 +1,6 @@
---
title: transform.Markdownify
description: Renders markdown to HTML.
description: Renders Markdown to HTML.
categories: []
keywords: []
action:
@@ -24,8 +24,8 @@ To keep the wrapping `p` tags for a single paragraph, use the [`RenderString`] m
[`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.
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]: /templates/render-hooks/
[Markdown render hooks]: /render-hooks/
[#9692]: https://github.com/gohugoio/hugo/issues/9692
{{% /note %}}

View File

@@ -46,10 +46,10 @@ assets/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $path := "data/books.json" }}
{{ with resources.Get $path }}
{{ with unmarshal . }}
{{ with . | transform.Unmarshal }}
{{ $data = . }}
{{ end }}
{{ else }}
@@ -75,10 +75,10 @@ content/
```
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $path := "books.json" }}
{{ with .Resources.Get $path }}
{{ with unmarshal . }}
{{ with . | transform.Unmarshal }}
{{ $data = . }}
{{ end }}
{{ else }}
@@ -95,7 +95,7 @@ content/
A remote resource is a file on a remote server, accessible via HTTP or HTTPS.
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $url := "https://example.org/books.json" }}
{{ with resources.GetRemote $url }}
{{ with .Err }}
@@ -112,8 +112,15 @@ A remote resource is a file on a remote server, accessible via HTTP or HTTPS.
{{ end }}
```
[resource]: /getting-started/glossary/#resource
[page bundle]: /content-management/page-bundles
{{% 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 %}}
## Options
@@ -166,7 +173,7 @@ When unmarshaling an XML file, do not include the root node when accessing data.
Get the remote data:
```go-html-template
{{ $data := "" }}
{{ $data := dict }}
{{ $url := "https://example.org/books/index.xml" }}
{{ with resources.GetRemote $url }}
{{ with .Err }}
@@ -182,7 +189,7 @@ Get the remote data:
Inspect the data structure:
```go-html-template
<pre>{{ jsonify (dict "indent" " ") $data }}</pre>
<pre>{{ debug.Dump $data }}</pre>
```
List the book titles:
@@ -245,7 +252,7 @@ Let's add a `lang` attribute to the `title` nodes of our RSS feed, and a namespa
After retrieving the remote data, inspect the data structure:
```go-html-template
<pre>{{ jsonify (dict "indent" " ") $data }}</pre>
<pre>{{ debug.Dump $data }}</pre>
```
Each item node looks like this:
@@ -288,5 +295,7 @@ Hugo renders this to:
</ul>
```
[`index`]: /functions/collections/indexfunction
[`index`]: /functions/collections/indexfunction/
[identifiers]: https://go.dev/ref/spec#Identifiers
[resource]: /getting-started/glossary/#resource
[page bundle]: /content-management/page-bundles/

View File

@@ -20,48 +20,44 @@ Use this function with both monolingual and multilingual configurations. The URL
- The `baseURL` in site configuration
- The language prefix, if any
In examples that follow, the project is multilingual with content in both Español (`es`) and English (`en`). The default language is Español. The returned values are from the English site.
In examples that follow, the project is multilingual with content in both English (`en`) and Spanish (`es`). The returned values are from the English site.
### Input does not begin with a slash
If the input does not begin with a slash, the resulting URL will be correct regardless of the `baseURL`.
If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your site configuration.
With `baseURL = https://example.org/`
```go-html-template
{{ absLangURL "" }} https://example.org/en/
{{ absLangURL "articles" }} https://example.org/en/articles
{{ absLangURL "style.css" }} https://example.org/en/style.css
{{ absLangURL "" }} https://example.org/en/
{{ absLangURL "articles" }} https://example.org/en/articles
{{ absLangURL "style.css" }} https://example.org/en/style.css
```
With `baseURL = https://example.org/docs/`
```go-html-template
{{ absLangURL "" }} https://example.org/docs/en/
{{ absLangURL "articles" }} https://example.org/docs/en/articles
{{ absLangURL "style.css" }} https://example.org/docs/en/style.css
{{ absLangURL "" }} https://example.org/docs/en/
{{ absLangURL "articles" }} https://example.org/docs/en/articles
{{ absLangURL "style.css" }} https://example.org/docs/en/style.css
```
### Input begins with a slash
If the input begins with a slash, the resulting URL will be incorrect when the `baseURL` includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the `baseURL`.
If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration.
With `baseURL = https://example.org/`
```go-html-template
{{ absLangURL "/" }} → https://example.org/en/
{{ absLangURL "/articles" }} → https://example.org/en/articles
{{ absLangURL "/style.css" }} → https://example.org/en/style.css
{{ absLangURL "/" }} → https://example.org/en/
{{ absLangURL "/articles" }} → https://example.org/en/articles
{{ absLangURL "/style.css" }} → https://example.org/en/style.css
```
With `baseURL = https://example.org/docs/`
```go-html-template
{{ absLangURL "/" }} → https://example.org/en/
{{ absLangURL "/articles" }} → https://example.org/en/articles
{{ absLangURL "/style.css" }} → https://example.org/en/style.css
{{ absLangURL "/" }} → https://example.org/en/
{{ absLangURL "/articles" }} → https://example.org/en/articles
{{ absLangURL "/style.css" }} → https://example.org/en/style.css
```
{{% note %}}
The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.
{{% /note %}}

View File

@@ -14,53 +14,49 @@ action:
aliases: [/functions/absurl]
---
With multilingual configurations, use the [`absLangURL`] function instead. The URL returned by this function depends on:
With multilingual configurations, use the [`urls.AbsLangURL`] function instead. The URL returned by this function depends on:
- Whether the input begins with a slash
- The `baseURL` in site configuration
### Input does not begin with a slash
If the input does not begin with a slash, the resulting URL will be correct regardless of the `baseURL`.
If the input does not begin with a slash, the path in the resulting URL will be relative to the `baseURL` in your site configuration.
With `baseURL = https://example.org/`
```go-html-template
{{ absURL "" }} https://example.org/
{{ absURL "articles" }} https://example.org/articles
{{ absURL "style.css" }} https://example.org/style.css
{{ absURL "" }} https://example.org/
{{ absURL "articles" }} https://example.org/articles
{{ absURL "style.css" }} https://example.org/style.css
```
With `baseURL = https://example.org/docs/`
```go-html-template
{{ absURL "" }} https://example.org/docs/
{{ absURL "articles" }} https://example.org/docs/articles
{{ absURL "style.css" }} https://example.org/docs/style.css
{{ absURL "" }} https://example.org/docs/
{{ absURL "articles" }} https://example.org/docs/articles
{{ absURL "style.css" }} https://example.org/docs/style.css
```
#### Input begins with a slash
If the input begins with a slash, the resulting URL will be incorrect when the `baseURL` includes a subdirectory. With a leading slash, the function returns a URL relative to the protocol+host section of the `baseURL`.
If the input begins with a slash, the path in the resulting URL will be relative to the protocol+host of the `baseURL` in your site configuration.
With `baseURL = https://example.org/`
```go-html-template
{{ absURL "/" }} → https://example.org/
{{ absURL "/articles" }} → https://example.org/articles
{{ absURL "/style.css" }} → https://example.org/style.css
{{ absURL "/" }} → https://example.org/
{{ absURL "/articles" }} → https://example.org/articles
{{ absURL "/style.css" }} → https://example.org/style.css
```
With `baseURL = https://example.org/docs/`
```go-html-template
{{ absURL "/" }} → https://example.org/
{{ absURL "/articles" }} → https://example.org/articles
{{ absURL "/style.css" }} → https://example.org/style.css
{{ absURL "/" }} → https://example.org/
{{ absURL "/articles" }} → https://example.org/articles
{{ absURL "/style.css" }} → https://example.org/style.css
```
{{% note %}}
The last three examples are not desirable in most situations. As a best practice, never include a leading slash when using this function.
{{% /note %}}
[`absLangURL`]: /functions/urls/abslangurl/
[`urls.AbsLangURL`]: /functions/urls/abslangurl/

View File

@@ -16,14 +16,14 @@ aliases: [/functions/anchorize]
## Sanitizing logic
With the default markdown renderer, Goldmark, the sanitizing logic is controlled by your site configuration:
With the default Markdown renderer, Goldmark, the sanitizing logic is controlled by your site configuration:
{{< code-toggle file=hugo >}}
[markup.goldmark.parser]
autoHeadingIDType = 'github'
{{< /code-toggle >}}
This controls the behavior of the `anchorize` function and the generation of heading IDs when rendering markdown to HTML.
This controls the behavior of the `anchorize` function and the generation of heading IDs when rendering Markdown to HTML.
Set `autoHeadingIDType` to one of:

Some files were not shown because too many files have changed in this diff Show More