docs: Prepare for new sub tree

See #11925
This commit is contained in:
Bjørn Erik Pedersen
2024-01-27 10:47:28 +01:00
parent 1083bf7c08
commit fc7de7136a
1157 changed files with 0 additions and 64232 deletions

View File

@@ -1,71 +0,0 @@
---
title: collections.After
description: Slices an array to the items after the Nth item.
categories: []
keywords: []
action:
aliases: [after]
related:
- functions/collections/First
- functions/collections/Last
returnType: any
signatures: [collections.After INDEX COLLECTION]
aliases: [/functions/after]
---
The following shows `after` being used in conjunction with the [`slice`]function:
```go-html-template
{{ $data := slice "one" "two" "three" "four" }}
<ul>
{{ range after 2 $data }}
<li>{{ . }}</li>
{{ end }}
</ul>
```
The template above is rendered to:
```html
<ul>
<li>three</li>
<li>four</li>
</ul>
```
## Example of `after` with `first`: 2nd&ndash;4th most recent articles
You can use `after` in combination with the [`first`] function and Hugo's [powerful sorting methods][lists]. Let's assume you have a list page at `example.com/articles`. You have 10 articles, but you want your templating for the [list/section page] to show only two rows:
1. The top row is titled "Featured" and shows only the most recently published article (i.e. by `publishdate` in the content files' front matter).
2. The second row is titled "Recent Articles" and shows only the 2nd- to 4th-most recently published articles.
{{< code file=layouts/section/articles.html >}}
{{ define "main" }}
<section class="row featured-article">
<h2>Featured Article</h2>
{{ range first 1 .Pages.ByPublishDate.Reverse }}
<header>
<h3><a href="{{ .RelPermalink }}">{{ .Title }}</a></h3>
</header>
<p>{{ .Description }}</p>
{{ end }}
</section>
<div class="row recent-articles">
<h2>Recent Articles</h2>
{{ range first 3 (after 1 .Pages.ByPublishDate.Reverse) }}
<section class="recent-article">
<header>
<h3><a href="{{ .RelPermalink }}">{{ .Title }}</a></h3>
</header>
<p>{{ .Description }}</p>
</section>
{{ end }}
</div>
{{ end }}
{{< /code >}}
[`first`]: /functions/collections/first
[list/section page]: /templates/section-templates
[lists]: /templates/lists/#sort-content
[`slice`]: /functions/collections/slice/

View File

@@ -1,101 +0,0 @@
---
title: collections.Append
description: Appends one or more elements to a slice and returns the resulting slice.
categories: []
keywords: []
action:
aliases: [append]
related:
- functions/collections/Merge
returnType: any
signatures:
- collections.Append ELEMENT [ELEMENT...] COLLECTION
- collections.Append COLLECTION1 COLLECTION2
aliases: [/functions/append]
---
This function appends all elements, excluding the last, to the last element. This allows [pipe](/getting-started/glossary/#pipeline) constructs as shown below.
Append a single element to a slice:
```go-html-template
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append "c" }}
{{ $s }} → [a b c]
```
Append two elements to a slice:
```go-html-template
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append "c" "d" }}
{{ $s }} → [a b c d]
```
Append two elements, as a slice, to a slice. This produces the same result as the previous example:
```go-html-template
{{ $s := slice "a" "b" }}
{{ $s }} → [a b]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [a b c d]
```
Start with an empty slice:
```go-html-template
{{ $s := slice }}
{{ $s }} → []
{{ $s = $s | append "a" }}
{{ $s }} → [a]
{{ $s = $s | append "b" "c" }}
{{ $s }} → [a b c]
{{ $s = $s | append (slice "d" "e") }}
{{ $s }} → [a b c d e]
```
If you start with a slice of a slice:
```go-html-template
{{ $s := slice (slice "a" "b") }}
{{ $s }} → [[a b]]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [[a b] [c d]]
```
To create a slice of slices, starting with an empty slice:
```go-html-template
{{ $s := slice }}
{{ $s }} → []
{{ $s = $s | append (slice (slice "a" "b")) }}
{{ $s }} → [[a b]]
{{ $s = $s | append (slice "c" "d") }}
{{ $s }} → [[a b] [c d]]
```
Although the elements in the examples above are strings, you can use the `append` function with any data type, including Pages. For example, on the home page of a corporate site, to display links to the two most recent press releases followed by links to the four most recent articles:
```go-html-template
{{ $p := where site.RegularPages "Type" "press-releases" | first 2 }}
{{ $p = $p | append (where site.RegularPages "Type" "articles" | first 4) }}
{{ with $p }}
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
```

View File

@@ -1,26 +0,0 @@
---
title: collections.Apply
description: Returns a new collection with each element transformed by the given function.
categories: []
keywords: []
action:
aliases: [apply]
related: []
returnType: '[]any'
signatures: [collections.Apply COLLECTION FUNCTION PARAM...]
aliases: [/functions/apply]
---
The `apply` function takes three or more arguments, depending on the function being applied to the collection elements.
The first argument is the collection itself, the second argument is the function name, and the remaining arguments are passed to the function, with the string `"."` representing the collection element.
```go-html-template
{{ $s := slice "hello" "world" }}
{{ $s = apply $s "strings.FirstUpper" "." }}
{{ $s }} → [Hello World]
{{ $s = apply $s "strings.Replace" "." "l" "_" }}
{{ $s }} → [He__o Wor_d]
```

View File

@@ -1,80 +0,0 @@
---
title: collections.Complement
description: Returns the elements of the last collection that are not in any of the others.
categories: []
keywords: []
action:
aliases: [complement]
related:
- functions/collections/Intersect
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: ['collections.Complement COLLECTION [COLLECTION...]']
aliases: [/functions/complement]
---
To find the elements within `$c3` that do not exist in `$c1` or `$c2`:
```go-html-template
{{ $c1 := slice 3 }}
{{ $c2 := slice 4 5 }}
{{ $c3 := slice 1 2 3 4 5 }}
{{ complement $c1 $c2 $c3 }} → [1 2]
```
{{% note %}}
Make your code simpler to understand by using a [chained pipeline]:
[chained pipeline]: https://pkg.go.dev/text/template#hdr-Pipelines
{{% /note %}}
```go-html-template
{{ $c3 | complement $c1 $c2 }} → [1 2]
```
You can also use the `complement` function with page collections. Let's say your site has five content types:
```text
content/
├── blog/
├── books/
├── faqs/
├── films/
└── songs/
```
To list everything except blog articles (`blog`) and frequently asked questions (`faqs`):
```go-html-template
{{ $blog := where site.RegularPages "Type" "blog" }}
{{ $faqs := where site.RegularPages "Type" "faqs" }}
{{ range site.RegularPages | complement $blog $faqs }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
```
{{% note %}}
Although the example above demonstrates the `complement` function, you could use the [`where`] function as well:
[`where`]: /functions/collections/where
{{% /note %}}
```go-html-template
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
{{ end }}
```
In this example we use the `complement` function to remove [stop words] from a sentence:
```go-html-template
{{ $text := "The quick brown fox jumps over the lazy dog" }}
{{ $stopWords := slice "a" "an" "in" "over" "the" "under" }}
{{ $filtered := split $text " " | complement $stopWords }}
{{ delimit $filtered " " }} → The quick brown fox jumps lazy dog
```
[stop words]: https://en.wikipedia.org/wiki/Stop_word

View File

@@ -1,33 +0,0 @@
---
title: collections.Delimit
description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.
categories: []
keywords: []
action:
aliases: [delimit]
related:
- functions/strings/Split
returnType: string
signatures: ['collections.Delimit COLLECTION DELIMITER [LAST]']
aliases: [/functions/delimit]
---
Delimit a slice:
```go-html-template
{{ $s := slice "b" "a" "c" }}
{{ delimit $s ", " }} → b, a, c
{{ delimit $s ", " " and "}} → b, a and c
```
Delimit a map:
{{% note %}}
The `delimit` function sorts maps by key, returning the values.
{{% /note %}}
```go-html-template
{{ $m := dict "b" 2 "a" 1 "c" 3 }}
{{ delimit $m ", " }} → 1, 2, 3
{{ delimit $m ", " " and "}} → 1, 2 and 3
```

View File

@@ -1,68 +0,0 @@
---
title: collections.Dictionary
description: Creates a map from a list of key and value pairs.
categories: []
keywords: []
action:
aliases: [dict]
related:
- functions/collections/Slice
returnType: mapany
signatures: ['collections.Dictionary KEY VALUE [VALUE...]']
aliases: [/functions/dict]
---
```go-html-template
{{ $m := dict "a" 1 "b" 2 }}
```
The above produces this data structure:
```json
{
"a": 1,
"b": 2
}
```
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.:
```go-html-template
{{ $m := dict (slice "a" "b" "c") "value" }}
```
The above produces this data structure:
```json
{
"a": {
"b": {
"c": "value"
}
}
}
```
## 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

@@ -1,37 +0,0 @@
---
title: collections.First
description: Returns the given collection, limited to the first N elements.
categories: []
keywords: []
action:
aliases: [first]
related:
- functions/collections/After
- functions/collections/Last
- methods/pages/Limit
returnType: any
signatures: [collections.First N COLLECTION]
aliases: [/functions/first]
---
```go-html-template
{{ range first 5 .Pages }}
{{ .Render "summary" }}
{{ end }}
```
Set `N` to zero to return an empty collection.
```go-html-template
{{ $emptyPageCollection := first 0 .Pages}}
```
Use `first` and [`where`] together.
```go-html-template
{{ range where .Pages "Section" "articles" | first 5 }}
{{ .Render "summary" }}
{{ end }}
```
[`where`]: /functions/collections/where

View File

@@ -1,31 +0,0 @@
---
title: collections.Group
description: Groups the given page collection by the given key.
categories: []
keywords: []
action:
aliases: [group]
related: []
returnType: any
signatures: [collections.Group KEY PAGES]
aliases: [/functions/group]
---
```go-html-template
{{ $new := .Site.RegularPages | first 10 | group "New" }}
{{ $old := .Site.RegularPages | last 10 | group "Old" }}
{{ $groups := slice $new $old }}
{{ range $groups }}
<h3>{{ .Key }}{{/* Prints "New", "Old" */}}</h3>
<ul>
{{ range .Pages }}
<li>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
```
The page group you get from `group` is of the same type you get from the built-in [group methods](/templates/lists#group-content) in Hugo. The above example can be [paginated](/templates/pagination/#list-paginator-pages).

View File

@@ -1,43 +0,0 @@
---
title: collections.In
description: Reports whether the given value is a member of the given set.
categories: []
keywords: []
action:
aliases: [in]
related:
- functions/strings/Contains
- functions/strings/ContainsAny
- functions/strings/ContainsNonSpace
- functions/strings/HasPrefix
- functions/strings/HasSuffix
returnType: bool
signatures: [collections.In SET VALUE]
aliases: [/functions/in]
---
The `SET` can be an [array], [slice], or [string].
[array]: /getting-started/glossary/#array
[slice]: /getting-started/glossary/#slice
[string]: /getting-started/glossary/#string
```go-html-template
{{ $s := slice "a" "b" "c" }}
{{ in $s "b" }} → true
```
```go-html-template
{{ $s := slice 1 2 3 }}
{{ in $s 2 }} → true
```
```go-html-template
{{ $s := slice 1.11 2.22 3.33 }}
{{ in $s 2.22 }} → true
```
```go-html-template
{{ $s := "abc" }}
{{ in $s "b" }} → true
```

View File

@@ -1,95 +0,0 @@
---
title: collections.Index
description: Looks up the index(es) or key(s) of the data structure passed into it.
categories: []
keywords: []
action:
aliases: [index]
related: []
returnType: any
signatures:
- collections.Index COLLECTION INDEXES
- collections.Index COLLECTION KEYS
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.:
```go-html-template
{{ $slice := slice "a" "b" "c" }}
{{ index $slice 0 }} → a
{{ index $slice 1 }} → b
{{ $map := dict "a" 100 "b" 200 }}
{{ index $map "b" }} → 200
```
The function takes multiple indices as arguments, and this can be used to get nested values, e.g.:
```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
```
You may write multiple indices as a slice:
```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $slice := slice "c" "e" }}
{{ index $map $slice }} → 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;
```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
```

View File

@@ -1,30 +0,0 @@
---
title: collections.Intersect
description: Returns the common elements of two arrays or slices, in the same order as the first array.
categories: []
keywords: []
action:
aliases: [intersect]
related:
- functions/collections/Complement
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: [collections.Intersect SET1 SET2]
aliases: [/functions/intersect]
---
A useful example is to use it as `AND` filters when combined with where:
```go-html-template
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages := $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages := $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page parameters.
See [union](/functions/collections/union) for `OR`.
[partials]: /templates/partials/
[single]: /templates/single-page-templates/

View File

@@ -1,45 +0,0 @@
---
title: collections.IsSet
description: Reports whether the key exists within the collection.
categories: []
keywords: []
action:
aliases: [isset]
related:
- functions/go-template/if
- functions/go-template/with
returnType: bool
signatures: [collections.IsSet COLLECTION KEY]
aliases: [/functions/isset]
---
For example, consider this site configuration:
{{< code-toggle file=hugo >}}
[params]
showHeroImage = false
{{< /code-toggle >}}
It the value of `showHeroImage` is `true`, we can detect that it exists using either `if` or `with`:
```go-html-template
{{ if site.Params.showHeroImage }}
{{ site.Params.showHeroImage }} → true
{{ end }}
{{ with site.Params.showHeroImage }}
{{ . }} → true
{{ end }}
```
But if the value of `showHeroImage` is `false`, we can't use either `if` or `with` to detect its existence. In this case, you must use the `isset` function:
```go-html-template
{{ if isset site.Params "showheroimage" }}
<p>The showHeroImage parameter is set to {{ site.Params.showHeroImage }}.<p>
{{ end }}
```
{{% note %}}
When using the `isset` function you must reference the key using lower case. See the previous example.
{{% /note %}}

View File

@@ -1,43 +0,0 @@
---
title: collections.KeyVals
description: Returns a KeyVals struct.
categories: []
keywords: []
action:
aliases: [keyVals]
related:
- methods/pages/Related
returnType: types.KeyValues
signatures: [collections.KeyVals KEY VALUES...]
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.
[`Related`]: /methods/pages/related
See [related content](/content-management/related).
```go-html-template
{{ $kv := keyVals "foo" "a" "b" "c" }}
```
The resulting data structure is:
```json
{
"Key": "foo",
"Values": [
"a",
"b",
"c"
]
}
```
To extract the key and values:
```go-html-template
{{ $kv.Key }} → foo
{{ $kv.Values }} → [a b c]
```

View File

@@ -1,34 +0,0 @@
---
title: collections.Last
description: Returns the given collection, limited to the last N elements.
categories: []
keywords: []
action:
aliases: [last]
related:
- functions/collections/After
- functions/collections/First
returnType: any
signatures: [collections.Last N COLLECTION]
aliases: [/functions/last]
---
```go-html-template
{{ range last 10 .Pages }}
{{ .Render "summary" }}
{{ end }}
```
Set `N` to zero to return an empty collection.
```go-html-template
{{ $emptyPageCollection := last 0 .Pages}}
```
Use `last` and [`where`] together.
```go-html-template
{{ range where .Pages "Section" "articles" | last 5 }}
{{ .Render "summary" }}
{{ end }}
```

View File

@@ -1,69 +0,0 @@
---
title: collections.Merge
description: Returns the result of merging two or more maps.
categories: []
keywords: []
action:
aliases: [merge]
related:
- functions/collections/Append
returnType: any
signatures: [collections.Merge MAP MAP...]
aliases: [/functions/merge]
---
Returns the result of merging two or more maps from left to right. If a key already exists, `merge` updates its value. If a key is absent, `merge` inserts the value under the new key.
Key handling is case-insensitive.
The following examples use these map definitions:
```go-html-template
{{ $m1 := dict "x" "foo" }}
{{ $m2 := dict "x" "bar" "y" "wibble" }}
{{ $m3 := dict "x" "baz" "y" "wobble" "z" (dict "a" "huey") }}
```
Example 1
```go-html-template
{{ $merged := merge $m1 $m2 $m3 }}
{{ $merged.x }} → baz
{{ $merged.y }} → wobble
{{ $merged.z.a }} → huey
```
Example 2
```go-html-template
{{ $merged := merge $m3 $m2 $m1 }}
{{ $merged.x }} → foo
{{ $merged.y }} → wibble
{{ $merged.z.a }} → huey
```
Example 3
```go-html-template
{{ $merged := merge $m2 $m3 $m1 }}
{{ $merged.x }} → foo
{{ $merged.y }} → wobble
{{ $merged.z.a }} → huey
```
Example 4
```go-html-template
{{ $merged := merge $m1 $m3 $m2 }}
{{ $merged.x }} → bar
{{ $merged.y }} → wibble
{{ $merged.z.a }} → huey
```
{{% note %}}
Regardless of depth, merging only applies to maps. For slices, use [append](/functions/collections/append).
{{% /note %}}

View File

@@ -1,124 +0,0 @@
---
title: collections.NewScratch
description: Returns a locally scoped "scratch pad" to store and manipulate data.
categories: []
keywords: []
action:
aliases: [newScratch]
related:
- methods/page/scratch
- methods/page/store
- methods/shortcode/scratch
returnType: maps.Scratch
signatures: [collections.NewScratch ]
---
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 pad]: /getting-started/glossary/#scratch-pad
## Methods
###### Set
Sets the value of a given key.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
```
###### Get
Gets the value of a given key.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.Get "greeting" }} → Hello
```
###### Add
Adds a given value to existing value(s) of the given key.
For single values, `Add` accepts values that support Go's `+` operator. If the first `Add` for a key is an array or slice, the following adds will be appended to that list.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.Add "greeting" "Welcome" }}
{{ $s.Get "greeting" }} → HelloWelcome
```
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "total" 3 }}
{{ $s.Add "total" 7 }}
{{ $s.Get "total" }} → 10
```
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greetings" (slice "Hello") }}
{{ $s.Add "greetings" (slice "Welcome" "Cheers") }}
{{ $s.Get "greetings" }} → [Hello Welcome Cheers]
```
###### SetInMap
Takes a `key`, `mapKey` and `value` and adds a map of `mapKey` and `value` to the given `key`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.Get "greetings" }} → map[english:Hello french:Bonjour]
```
###### DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.DeleteInMap "greetings" "english" }}
{{ $s.Get "greetings" }} → map[french:Bonjour]
```
###### GetSortedMapValues
Returns an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $s.GetSortedMapValues "greetings" }} → [Hello Bonjour]
```
###### Delete
Removes the given key.
```go-html-template
{{ $s := newScratch }}
{{ $s.Set "greeting" "Hello" }}
{{ $s.Delete "greeting" }}
```
###### Values
Returns the raw backing map. Do not use with `Scratch` or `Store` methods on a `Page` object due to concurrency issues.
```go-html-template
{{ $s := newScratch }}
{{ $s.SetInMap "greetings" "english" "Hello" }}
{{ $s.SetInMap "greetings" "french" "Bonjour" }}
{{ $map := $s.Values }}
```

View File

@@ -1,32 +0,0 @@
---
title: collections.Querify
description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs.
categories: []
keywords: []
action:
aliases: [querify]
related:
- functions/go-template/urlquery.md
returnType: string
signatures:
- collections.Querify VALUE [VALUE...]
- collections.Querify COLLECTION
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.
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>
```
Both of these examples render the following HTML:
```html
<a href="https://www.google.com?page=3&q=test">Search</a>
```

View File

@@ -1,19 +0,0 @@
---
title: collections.Reverse
description: Reverses the order of a collection.
categories: []
keywords: []
action:
aliases: []
related:
- functions/collections/Sort
- functions/collections/Shuffle
- functions/collections/Uniq
returnType: any
signatures: [collections.Reverse COLLECTION]
aliases: [/functions/collections.reverse]
---
```go-html-template
{{ slice 2 1 3 | collections.Reverse }} → [3 1 2]
```

View File

@@ -1,36 +0,0 @@
---
title: collections.Seq
description: Returns a slice of integers.
categories: []
keywords: []
action:
aliases: [seq]
related: []
returnType: '[]int'
signatures:
- collections.Seq LAST
- collections.Seq FIRST LAST
- collections.Seq FIRST INCREMENT LAST
aliases: [/functions/seq]
---
```go-html-template
{{ seq 2 }} → [1 2]
{{ seq 0 2 }} → [0 1 2]
{{ seq -2 2 }} → [-2 -1 0 1 2]
{{ seq -2 2 2 }} → [-2 0 2]
```
A contrived example of iterating over a sequence of integers:
```go-html-template
{{ $product := 1 }}
{{ range seq 4 }}
{{ $product = mul $product . }}
{{ end }}
{{ $product }} → 24
```
{{% note %}}
The slice created by the `seq` function is limited to 2000 elements.
{{% /note %}}

View File

@@ -1,22 +0,0 @@
---
title: collections.Shuffle
description: Returns a random permutation of a given array or slice.
categories: []
keywords: []
action:
aliases: [shuffle]
related:
- functions/collections/Reverse
- functions/collections/Sort
- functions/collections/Uniq
returnType: any
signatures: [collections.Shuffle COLLECTION]
aliases: [/functions/shuffle]
---
```go-html-template
{{ shuffle (seq 1 2 3) }} → [3 1 2]
{{ shuffle (slice "a" "b" "c") }} → [b a c]
```
The result will vary from one build to the next.

View File

@@ -1,18 +0,0 @@
---
title: collections.Slice
description: Creates a slice of all passed arguments.
categories: []
keywords: []
action:
aliases: [slice]
related:
- functions/collections/Dictionary
returnType: any
signatures: [collections.Slice ITEM...]
aliases: [/functions/slice]
---
```go-html-template
{{ $s := slice "a" "b" "c" }}
{{ $s }} → [a b c]
```

View File

@@ -1,156 +0,0 @@
---
title: collections.Sort
description: Sorts slices, maps, and page collections.
categories: []
keywords: []
action:
aliases: [sort]
related:
- functions/collections/Reverse
- functions/collections/Shuffle
- functions/collections/Uniq
returnType: any
signatures: ['collections.Sort COLLECTION [KEY] [ORDER]']
toc: true
aliases: [/functions/sort]
---
The `KEY` is optional when sorting slices in ascending order, otherwise it is required. When sorting slices, use the literal `value` in place of the `KEY`. See examples below.
The `ORDER` may be either `asc` (ascending) or `desc` (descending). The default sort order is ascending.
## Sort a slice
The examples below assume this site configuration:
{{< code-toggle file=hugo >}}
[params]
grades = ['b','a','c']
{{< /code-toggle >}}
### Ascending order {#slice-ascending-order}
Sort slice elements in ascending order using either of these constructs:
```go-html-template
{{ sort site.Params.grades }} → [a b c]
{{ sort site.Params.grades "value" "asc" }} → [a b c]
```
In the examples above, `value` is the `KEY` representing the value of the slice element.
### Descending order {#slice-descending-order}
Sort slice elements in descending order:
```go-html-template
{{ sort site.Params.grades "value" "desc" }} → [c b a]
```
In the example above, `value` is the `KEY` representing the value of the slice element.
## Sort a map
The examples below assume this site configuration:
{{< code-toggle file=hugo >}}
[params.authors.a]
firstName = "Marius"
lastName = "Pontmercy"
[params.authors.b]
firstName = "Victor"
lastName = "Hugo"
[params.authors.c]
firstName = "Jean"
lastName = "Valjean"
{{< /code-toggle >}}
{{% note %}}
When sorting maps, the `KEY` argument must be lowercase.
{{% /note %}}
### Ascending order {#map-ascending-order}
Sort map objects in ascending order using either of these constructs:
```go-html-template
{{ range sort site.Params.authors "firstname" }}
{{ .firstName }}
{{ end }}
{{ range sort site.Params.authors "firstname" "asc" }}
{{ .firstName }}
{{ end }}
```
These produce:
```text
Jean Marius Victor
```
### Descending order {#map-descending-order}
Sort map objects in descending order:
```go-html-template
{{ range sort site.Params.authors "firstname" "desc" }}
{{ .firstName }}
{{ end }}
```
This produces:
```text
Victor Marius Jean
```
### First level key removal
Hugo removes the first level keys when sorting a map.
Original map:
```json
{
"felix": {
"breed": "malicious",
"type": "cat"
},
"spot": {
"breed": "boxer",
"type": "dog"
}
}
```
After sorting:
```json
[
{
"breed": "malicious",
"type": "cat"
},
{
"breed": "boxer",
"type": "dog"
}
]
```
## Sort a page collection
{{% 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
{{% /note %}}
In this contrived example, sort the site's regular pages by `.Type` in descending order:
```go-html-template
{{ range sort site.RegularPages "Type" "desc" }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
```

View File

@@ -1,24 +0,0 @@
---
title: collections.SymDiff
description: Returns the symmetric difference of two collections.
categories: []
keywords: []
action:
aliases: [symdiff]
related:
- functions/collections/Complement
- functions/collections/Intersect
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: [COLLECTION | collections.SymDiff COLLECTION]
aliases: [/functions/symdiff]
---
Example:
```go-html-template
{{ slice 1 2 3 | symdiff (slice 3 4) }} → [1 2 4]
```
Also see <https://en.wikipedia.org/wiki/Symmetric_difference>.

View File

@@ -1,46 +0,0 @@
---
title: collections.Union
description: Given two arrays or slices, returns a new array that contains the elements that belong to either or both arrays/slices.
categories: []
keywords: []
action:
aliases: [union]
related:
- functions/collections/Complement
- functions/collections/Intersect
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: [collections.Union SET1 SET2]
aliases: [/functions/union]
---
Given two arrays (or slices) A and B, this function will return a new array that contains the elements or objects that belong to either A or to B or to both.
```go-html-template
{{ union (slice 1 2 3) (slice 3 4 5) }}
<!-- returns [1 2 3 4 5] -->
{{ union (slice 1 2 3) nil }}
<!-- returns [1 2 3] -->
{{ union nil (slice 1 2 3) }}
<!-- returns [1 2 3] -->
{{ union nil nil }}
<!-- returns an error because both arrays/slices have to be of the same type -->
```
## OR filter in where query
This is also very useful to use as `OR` filters when combined with where:
```go-html-template
{{ $pages := where .Site.RegularPages "Type" "not in" (slice "page" "about") }}
{{ $pages = $pages | union (where .Site.RegularPages "Params.pinned" true) }}
{{ $pages = $pages | intersect (where .Site.RegularPages "Params.images" "!=" nil) }}
```
The above fetches regular pages not of `page` or `about` type unless they are pinned. And finally, we exclude all pages with no `images` set in Page parameters.
See [intersect](/functions/collections/intersect) for `AND`.

View File

@@ -1,20 +0,0 @@
---
title: collections.Uniq
description: Returns the given collection, removing duplicate elements.
categories: []
keywords: []
action:
aliases: [uniq]
related:
- functions/collections/Reverse
- functions/collections/Shuffle
- functions/collections/Sort
- functions/collections/Uniq
returnType: any
signatures: [collections.Uniq COLLECTION]
aliases: [/functions/uniq]
---
```go-html-template
{{ slice 1 3 2 1 | uniq }} → [1 3 2]
```

View File

@@ -1,446 +0,0 @@
---
title: collections.Where
description: Returns the given collection, removing elements that do not satisfy the comparison condition.
categories: []
keywords: []
action:
aliases: [where]
related: []
returnType: any
signatures: ['collections.Where COLLECTION KEY [OPERATOR] VALUE']
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:
```text
collections.Where COLLECTION KEY [OPERATOR] VALUE
--------------------
comparison condition
```
Hugo will test for equality if you do not provide an `OPERATOR` argument. For example:
```go-html-template
{{ $pages := where .Site.RegularPages "Section" "books" }}
{{ $books := where .Site.Data.books "genres" "suspense" }}
```
## Arguments
The where function takes three or four arguments. The `OPERATOR` argument is optional.
COLLECTION
: (`any`) A [page collection] or a [slice] of [maps].
[maps]: /getting-started/glossary/#map
[page collection]: /getting-started/glossary/#page-collection
[slice]: /getting-started/glossary/#slice
KEY
: (`string`) The key of the page or map value to compare with `VALUE`. With page collections, commonly used comparison keys are `Section`, `Type`, and `Params`. To compare with a member of the page `Params` map, [chain] the subkey as shown below:
```go-html-template
{{ $result := where .Site.RegularPages "Params.foo" "bar" }}
```
[chain]: /getting-started/glossary/#chain
Typically a
OPERATOR
: (`string`) The logical comparison [operator](#operators).
VALUE
: (`any`) The value with which to compare. The values to compare must have comparable data types. For example:
Comparison|Result
:--|:--
`"123" "eq" "123"`|`true`
`"123" "eq" 123`|`false`
`false "eq" "false"`|`false`
`false "eq" false`|`true`
When one or both of the values to compare is a slice, use the `in`, `not in`, or `intersect` operators as described below.
## Operators
Use any of the following logical operators:
`=`, `==`, `eq`
: (`bool`) Reports whether the given field value is equal to `VALUE`.
`!=`, `<>`, `ne`
: (`bool`) Reports whether the given field value is not equal to `VALUE`.
`>=`, `ge`
: (`bool`) Reports whether the given field value is greater than or equal to `VALUE`.
`>`, `gt`
: `true` Reports whether the given field value is greater than `VALUE`.
`<=`, `le`
: (`bool`) Reports whether the given field value is less than or equal to `VALUE`.
`<`, `lt`
: (`bool`) Reports whether the given field value is less than `VALUE`.
`in`
: (`bool`) Reports whether the given field value is a member of `VALUE`. Compare string to slice, or string to string. See&nbsp;[details](/functions/collections/in).
`not in`
: (`bool`) Reports whether the given field value is not a member of `VALUE`. Compare string to slice, or string to string. See&nbsp;[details](/functions/collections/in).
`intersect`
: (`bool`) Reports whether the given field value (a slice) contains one or more elements in common with `VALUE`. See&nbsp;[details](/functions/collections/intersect).
`like` {{< new-in 0.116.0 >}}
: (`bool`) Reports whether the given field value matches the regular expression specified in `VALUE`. Use the `like` operator to compare `string` values. The `like` operator returns `false` when comparing other data types to the regular expression.
{{% note %}}
The examples below perform comparisons within a page collection, but the same comparisons are applicable to a slice of maps.
{{% /note %}}
## String comparison
Compare the value of the given field to a [`string`]:
[`string`]: /getting-started/glossary/#string
```go-html-template
{{ $pages := where .Site.RegularPages "Section" "eq" "books" }}
{{ $pages := where .Site.RegularPages "Section" "ne" "books" }}
```
## Numeric comparison
Compare the value of the given field to an [`int`] or [`float`]:
[`int`]: /getting-started/glossary/#int
[`float`]: /getting-started/glossary/#float
```go-html-template
{{ $books := where site.RegularPages "Section" "eq" "books" }}
{{ $pages := where $books "Params.price" "eq" 42 }}
{{ $pages := where $books "Params.price" "ne" 42.67 }}
{{ $pages := where $books "Params.price" "ge" 42 }}
{{ $pages := where $books "Params.price" "gt" 42.67 }}
{{ $pages := where $books "Params.price" "le" 42 }}
{{ $pages := where $books "Params.price" "lt" 42.67 }}
```
## Boolean comparison
Compare the value of the given field to a [`bool`]:
[`bool`]: /getting-started/glossary/#bool
```go-html-template
{{ $books := where site.RegularPages "Section" "eq" "books" }}
{{ $pages := where $books "Params.fiction" "eq" true }}
{{ $pages := where $books "Params.fiction" "eq" false }}
{{ $pages := where $books "Params.fiction" "ne" true }}
{{ $pages := where $books "Params.fiction" "ne" false }}
```
## Member comparison
Compare a [`scalar`] to a [`slice`].
[`scalar`]: /getting-started/glossary/#scalar
[`slice`]: /getting-started/glossary/#slice
For example, to return a collection of pages where the `color` page parameter is either "red" or "yellow":
```go-html-template
{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}
{{ $colors := slice "red" "yellow" }}
{{ $pages := where $fruit "Params.color" "in" $colors }}
```
To return a collection of pages where the "color" page parameter is neither "red" nor "yellow":
```go-html-template
{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}
{{ $colors := slice "red" "yellow" }}
{{ $pages := where $fruit "Params.color" "not in" $colors }}
```
## Intersection comparison
Compare a [`slice`] to a [`slice`], returning collection elements with common values. This is frequently used when comparing taxonomy terms.
For example, to return a collection of pages where any of the terms in the "genres" taxonomy are "suspense" or "romance":
```go-html-template
{{ $books := where site.RegularPages "Section" "eq" "books" }}
{{ $genres := slice "suspense" "romance" }}
{{ $pages := where $books "Params.genres" "intersect" $genres }}
```
## Regular expression comparison
{{< new-in 0.116.0 >}}
To return a collection of pages where the "author" page parameter begins with either "victor" or "Victor":
```go-html-template
{{ $pages := where .Site.RegularPages "Params.author" "like" `(?i)^victor` }}
```
{{% include "functions/_common/regular-expressions.md" %}}
{{% note %}}
Use the `like` operator to compare string values. Comparing other data types will result in an empty collection.
{{% /note %}}
## Date comparison
### Predefined dates
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
[`time.Time`]: https://pkg.go.dev/time#Time
For example, to return a collection of pages that were created before the current year:
```go-html-template
{{ $startOfYear := time.AsTime (printf "%d-01-01" now.Year) }}
{{ $pages := where .Site.RegularPages "Date" "lt" $startOfYear }}
```
### Custom dates
With custom front matter dates, the comparison depends on the front matter data format (TOML, YAML, or JSON).
{{% note %}}
Using TOML for pages with custom front matter dates enables precise date comparisons.
{{% /note %}}
With TOML, date values are first-class citizens. TOML has a date data type while JSON and YAML do not. If you quote a TOML date, it is a string. If you do not quote a TOML date value, it is [`time.Time`] value, enabling precise comparisons.
In the TOML example below, note that the event date is not quoted.
{{< code file="content/events/2024-user-conference.md" >}}
+++
title = '2024 User Conference"
eventDate = 2024-04-01
+++
{{< /code >}}
To return a collection of future events:
```go-html-template
{{ $events := where .Site.RegularPages "Type" "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:
```go-html-template
{{ $events := where .Site.RegularPages "Type" "events" }}
{{ $futureEvents := slice }}
{{ range $events }}
{{ if gt (time.AsTime .Params.eventDate) now }}
{{ $futureEvents = $futureEvents | append . }}
{{ end }}
{{ end }}
```
## Nil comparison
To return a collection of pages where the "color" parameter is present in front matter, compare to `nil`:
```go-html-template
{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }}
```
To return a collection of pages where the "color" parameter is not present in front matter, compare to `nil`:
```go-html-template
{{ $pages := where .Site.RegularPages "Params.color" "eq" nil }}
```
In both examples above, note that `nil` is not quoted.
## Nested comparison
These are equivalent:
```go-html-template
{{ $pages := where .Site.RegularPages "Type" "tutorials" }}
{{ $pages = where $pages "Params.level" "eq" "beginner" }}
```
```go-html-template
{{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }}
```
## Portable section comparison
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
```go-html-template
{{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }}
```
With this construct, a theme author can instruct users to specify their main sections in the site configuration:
{{< code-toggle file=hugo >}}
[params]
mainSections = ['blog','galleries']
{{< /code-toggle >}}
If `params.mainSections` is not defined in the site configuration, the `MainSections` method returns a slice with one element---the top level section with the most pages.
## Boolean/undefined comparison
Consider this site content:
```text
content/
├── posts/
│ ├── _index.md
│ ├── post-1.md <-- front matter: exclude = false
│ ├── post-2.md <-- front matter: exclude = true
│ └── post-3.md <-- front matter: exclude not defined
└── _index.md
```
The first two pages have an "exclude" field in front matter, but the last page does not. When testing for _equality_, the third page is _excluded_ from the result. When testing for _inequality_, the third page is _included_ in the result.
### Equality test
This template:
```go-html-template
<ul>
{{ range where .Site.RegularPages "Params.exclude" "eq" false }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-1/">Post 1</a></li>
</ul>
```
This template:
```go-html-template
<ul>
{{ range where .Site.RegularPages "Params.exclude" "eq" true }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-2/">Post 2</a></li>
</ul>
```
### Inequality test
This template:
```go-html-template
<ul>
{{ range where .Site.RegularPages "Params.exclude" "ne" false }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-2/">Post 2</a></li>
<li><a href="/posts/post-3/">Post 3</a></li>
</ul>
```
This template:
```go-html-template
<ul>
{{ range where .Site.RegularPages "Params.exclude" "ne" true }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-1/">Post 1</a></li>
<li><a href="/posts/post-3/">Post 3</a></li>
</ul>
```
To exclude a page with an undefined field from a boolean _inequality_ test:
1. Create a collection using a boolean comparison
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
This template:
```go-html-template
{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" true }}
{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }}
<ul>
{{ range $p1 | complement $p2 }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-1/">Post 1</a></li>
</ul>
```
This template:
```go-html-template
{{ $p1 := where .Site.RegularPages "Params.exclude" "ne" false }}
{{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }}
<ul>
{{ range $p1 | complement $p2 }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
```
Is rendered to:
```html
<ul>
<li><a href="/posts/post-1/">Post 2</a></li>
</ul>
```

View File

@@ -1,12 +0,0 @@
---
title: Collections functions
linkTitle: collections
description: Template functions to work with arrays, slices, maps, and page collections.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to work with arrays, slices, maps, and page collections.