Merge commit '35dec7c96f7ee3eb17dd444f7067f0c776fb56ae'

This commit is contained in:
Bjørn Erik Pedersen
2023-12-04 15:24:01 +01:00
810 changed files with 24147 additions and 7766 deletions

View File

@@ -1,41 +0,0 @@
---
title: .AddDate
description: Returns the time corresponding to adding the given number of years, months, and days to the given time.Time value.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: time.Time
signatures: [.AddDate YEARS MONTHS DAYS]
relatedFunctions: []
---
```go-html-template
{{ $d := "2022-01-01" | time.AsTime }}
{{ $d.AddDate 0 0 1 | time.Format "2006-01-02" }} → 2022-01-02
{{ $d.AddDate 0 1 1 | time.Format "2006-01-02" }} → 2022-02-02
{{ $d.AddDate 1 1 1 | time.Format "2006-01-02" }} → 2023-02-02
{{ $d.AddDate -1 -1 -1 | time.Format "2006-01-02" }} → 2020-11-30
```
{{% note %}}
When adding months or years, Hugo normalizes the final `time.Time` value if the resulting day does not exist. For example, adding one month to 31 January produces 2 March or 3 March, depending on the year.
See [this explanation](https://github.com/golang/go/issues/31145#issuecomment-479067967) from the Go team.
{{% /note %}}
```go-html-template
{{ $d := "2023-01-31" | time.AsTime }}
{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} → 2023-03-03
{{ $d := "2024-01-31" | time.AsTime }}
{{ $d.AddDate 0 1 0 | time.Format "2006-01-02" }} → 2024-03-02
{{ $d := "2024-02-29" | time.AsTime }}
{{ $d.AddDate 1 0 0 | time.Format "2006-01-02" }} → 2025-03-01
```

View File

@@ -1,90 +0,0 @@
---
title: .Format
description: Returns a formatted time.Time value.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: string
signatures: [.Format LAYOUT]
relatedFunctions: []
toc: true
---
```go-template
{{ $t := "2023-01-27T23:44:58-08:00" }}
{{ $t = time.AsTime $t }}
{{ $format := "2 Jan 2006" }}
{{ $t.Format $format }} → 27 Jan 2023
```
{{% note %}}
To return a formatted and localized `time.Time` value, use the [`time.Format`] function instead.
[`time.Format`]: /functions/time/format
{{% /note %}}
Use the `.Format` method with any `time.Time` value, including the four predefined front matter dates:
```go-html-template
{{ $format := "2 Jan 2006" }}
{{ .Date.Format $format }}
{{ .PublishDate.Format $format }}
{{ .ExpiryDate.Format $format }}
{{ .Lastmod.Format $format }}
```
## Layout string
{{% readfile file="/functions/_common/time-layout-string.md" %}}
## Examples
Given this front matter:
{{< code-toggle fm=true copy=false >}}
title = "About time"
date = 2023-01-27T23:44:58-08:00
{{< /code-toggle >}}
The examples below were rendered in the `America/Los_Angeles` time zone:
Format string|Result
:--|:--
`Monday, January 2, 2006`|`Friday, January 27, 2023`
`Mon Jan 2 2006`|`Fri Jan 27 2023`
`January 2006`|`January 2023`
`2006-01-02`|`2023-01-27`
`Monday`|`Friday`
`02 Jan 06 15:04 MST`|`27 Jan 23 23:44 PST`
`Mon, 02 Jan 2006 15:04:05 MST`|`Fri, 27 Jan 2023 23:44:58 PST`
`Mon, 02 Jan 2006 15:04:05 -0700`|`Fri, 27 Jan 2023 23:44:58 -0800`
## UTC and local time
Convert and format any `time.Time` value to either Coordinated Universal Time (UTC) or local time.
```go-html-template
{{ $t := "2023-01-27T23:44:58-08:00" }}
{{ $t = time.AsTime $t }}
{{ $format := "2 Jan 2006 3:04:05 PM MST" }}
{{ $t.UTC.Format $format }} → 28 Jan 2023 7:44:58 AM UTC
{{ $t.Local.Format $format }} → 27 Jan 2023 11:44:58 PM PST
```
## Ordinal representation
Use the [`humanize`](/functions/inflect/humanize) function to render the day of the month as an ordinal number:
```go-html-template
{{ $t := "2023-01-27T23:44:58-08:00" }}
{{ $t = time.AsTime $t }}
{{ humanize $t.Day }} of {{ $t.Format "January 2006" }} → 27th of January 2023
```

View File

@@ -1,26 +0,0 @@
---
title: .Get
description: Accesses positional and ordered parameters in shortcode declaration.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: any
signatures:
- .Get INDEX
- .Get KEY
relatedFunctions: []
---
`.Get` is specifically used when creating your own [shortcode template][sc], to access the [positional and named](/templates/shortcode-templates/#positional-vs-named-parameters) parameters passed to it. When used with a numeric INDEX, it queries positional parameters (starting with 0). With a string KEY, it queries named parameters.
When accessing named or positional parameters that do not exist, `.Get` returns an empty string instead of interrupting the build. This allows you to chain `.Get` with `if`, `with`, `default` or `cond` to check for parameter existence. For example:
```go-html-template
{{ $quality := default "100" (.Get 1) }}
```
[sc]: /templates/shortcode-templates/

View File

@@ -1,84 +0,0 @@
---
title: .GetPage
description: Gets a `Page` of a given `path`.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType:
signatures: [.GetPage PATH]
relatedFunctions: []
---
`.GetPage` returns a page of a given `path`. Both `Site` and `Page` implements this method. The `Page` variant will, if given a relative path -- i.e. a path without a leading `/` -- try look for the page relative to the current page.
{{% note %}}
**Note:** We overhauled and simplified the `.GetPage` API in Hugo 0.45. Before that you needed to provide a `Kind` attribute in addition to the path, e.g. `{{ .Site.GetPage "section" "blog" }}`. This will still work, but is now superfluous.
{{% /note %}}
```go-html-template
{{ with .Site.GetPage "/blog" }}{{ .Title }}{{ end }}
```
This method will return `nil` when no page could be found, so the above will not print anything if the blog section is not found.
To find a regular page in the blog section::
```go-html-template
{{ with .Site.GetPage "/blog/my-post.md" }}{{ .Title }}{{ end }}
```
And since `Page` also provides a `.GetPage` method, the above is the same as:
```go-html-template
{{ with .Site.GetPage "/blog" }}
{{ with .GetPage "my-post.md" }}{{ .Title }}{{ end }}
{{ end }}
```
## .GetPage and multilingual sites
The previous examples have used the full content file name to look up the post. Depending on how you have organized your content (whether you have the language code in the file name or not, e.g. `my-post.en.md`), you may want to do the lookup without extension. This will get you the current language's version of the page:
```go-html-template
{{ with .Site.GetPage "/blog/my-post" }}{{ .Title }}{{ end }}
```
## .GetPage example
This code snippet---in the form of a [partial template][partials]---allows you to do the following:
1. Grab the index object of your `tags` [taxonomy].
2. Assign this object to a variable, `$t`
3. Sort the terms associated with the taxonomy by popularity.
4. Grab the top two most popular terms in the taxonomy (i.e., the two most popular tags assigned to content.
{{< code file="grab-top-two-tags.html" >}}
<ul class="most-popular-tags">
{{ $t := .Site.GetPage "/tags" }}
{{ range first 2 $t.Data.Terms.ByCount }}
<li>{{ . }}</li>
{{ end }}
</ul>
{{< /code >}}
## `.GetPage` on page bundles
If the page retrieved by `.GetPage` is a [Leaf Bundle][leaf_bundle], and you
need to get the nested _**page** resources_ in that, you will need to use the
methods in `.Resources` as explained in the [Page Resources][page_resources]
section.
See the [Headless Bundle][headless_bundle] documentation for an example.
[partials]: /templates/partials/
[taxonomy]: /content-management/taxonomies/
[page_kinds]: /templates/section-templates/#page-kinds
[leaf_bundle]: /content-management/page-bundles/#leaf-bundles
[headless_bundle]: /content-management/page-bundles/#headless-bundle
[page_resources]: /content-management/page-resources/

View File

@@ -1,35 +0,0 @@
---
title: .HasMenuCurrent
description: Reports whether the given page object matches the page object associated with one of the child menu entries under the given menu entry in the given menu.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: bool
signatures: [PAGE.HasMenuCurrent MENU MENUENTRY]
relatedFunctions:
- .HasMenuCurrent
- .IsMenuCurrent
---
If the page object associated with the menu entry is a section, this method also returns `true` for any descendant of that section.
```go-html-template
{{ $currentPage := . }}
{{ range site.Menus.main }}
{{ if $currentPage.IsMenuCurrent .Menu . }}
<a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a>
{{ else if $currentPage.HasMenuCurrent .Menu . }}
<a class="ancestor" aria-current="true" href="{{ .URL }}">{{ .Name }}</a>
{{ else }}
<a href="{{ .URL }}">{{ .Name }}</a>
{{ end }}
{{ end }}
```
See [menu templates] for a complete example.
[menu templates]: /templates/menu-templates/#example

View File

@@ -1,33 +0,0 @@
---
title: .IsMenuCurrent
description: Reports whether the given page object matches the page object associated with the given menu entry in the given menu.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: bool
signatures: [PAGE.IsMenuCurrent MENU MENUENTRY]
relatedFunctions:
- .HasMenuCurrent
- .IsMenuCurrent
---
```go-html-template
{{ $currentPage := . }}
{{ range site.Menus.main }}
{{ if $currentPage.IsMenuCurrent .Menu . }}
<a class="active" aria-current="page" href="{{ .URL }}">{{ .Name }}</a>
{{ else if $currentPage.HasMenuCurrent .Menu . }}
<a class="ancestor" aria-current="true" href="{{ .URL }}">{{ .Name }}</a>
{{ else }}
<a href="{{ .URL }}">{{ .Name }}</a>
{{ end }}
{{ end }}
```
See [menu templates] for a complete example.
[menu templates]: /templates/menu-templates/#example

View File

@@ -1,50 +0,0 @@
---
title: .Param
description: Returns a page parameter, falling back to a site parameter if present.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: any
signatures: [.Param KEY]
relatedFunctions: []
---
The `.Param` method on `.Page` looks for the given `KEY` in page parameters, and returns the corresponding value. If it cannot find the `KEY` in page parameters, it looks for the `KEY` in site parameters. If it cannot find the `KEY` in either location, the `.Param` method returns `nil`.
Site and theme developers commonly set parameters at the site level, allowing content authors to override those parameters at the page level.
For example, to show a table of contents on every page, but allow authors to hide the table of contents as needed:
**Configuration**
{{< code-toggle file="hugo" copy=false >}}
[params]
display_toc = true
{{< /code-toggle >}}
**Content**
{{< code-toggle file="content/example.md" fm=true copy=false >}}
title = 'Example'
date = 2023-01-01
draft = false
display_toc = false
{{< /code-toggle >}}
**Template**
{{< code file="layouts/_default/single.html" copy=false >}}
{{ if .Param "display_toc" }}
{{ .TableOfContents }}
{{ end }}
{{< /code >}}
The `.Param` method returns the value associated with the given `KEY`, regardless of whether the value is truthy or falsy. If you need to ignore falsy values, use this construct instead:
{{< code file="layouts/_default/single.html" copy=false >}}
{{ or .Params.foo site.Params.foo }}
{{< /code >}}

View File

@@ -1,28 +0,0 @@
---
title: .Render
description: Takes a view to apply when rendering content.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: template.HTML
signatures: [.Render LAYOUT]
relatedFunctions: []
---
The view is an alternative layout and should be a file name that points to a template in one of the locations specified in the documentation for [Content Views](/templates/views).
This function is only available when applied to a single piece of content within a [list context].
This example could render a piece of content using the content view located at `/layouts/_default/summary.html`:
```go-html-template
{{ range .Pages }}
{{ .Render "summary" }}
{{ end }}
```
[list context]: /templates/lists/

View File

@@ -1,35 +0,0 @@
---
title: .RenderString
description: Renders markup to HTML.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType: template.HTML
signatures: ['.RenderString MARKUP [OPTIONS]']
---
`.RenderString` is a method on `Page` that renders some markup to HTML using the content renderer defined for that page (if not set in the options).
The method takes an optional map argument with these options:
display ("inline")
: `inline` or `block`. If `inline` (default), surrounding `<p></p>` on short snippets will be trimmed.
markup (defaults to the Page's markup)
: See identifiers in [List of content formats](/content-management/formats/#list-of-content-formats).
Some examples:
```go-html-template
{{ $optBlock := dict "display" "block" }}
{{ $optOrg := dict "markup" "org" }}
{{ "**Bold Markdown**" | $p.RenderString }}
{{ "**Bold Block Markdown**" | $p.RenderString $optBlock }}
{{ "/italic org mode/" | $p.RenderString $optOrg }}
```
{{< new-in "0.93.0" >}} **Note**: [markdownify](/functions/transform/markdownify) uses this function in order to support [Render Hooks](/getting-started/configuration-markup/#markdown-render-hooks).

View File

@@ -1,151 +0,0 @@
---
title: .Scratch
description: Acts as a "scratchpad" to store and manipulate data.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType:
signatures: []
relatedFunctions:
- .Store
- .Scratch
aliases: [/extras/scratch/,/doc/scratch/]
---
Scratch is a Hugo feature designed to conveniently manipulate data in a Go Template world. It is either a Page or Shortcode method for which the resulting data will be attached to the given context, or it can live as a unique instance stored in a variable.
{{% note %}}
Note that Scratch was initially created as a workaround for a [Go template scoping limitation](https://github.com/golang/go/issues/10608) that affected Hugo versions prior to 0.48. For a detailed analysis of `.Scratch` and contextual use cases, see [this blog post](https://regisphilibert.com/blog/2017/04/hugo-scratch-explained-variable/).
{{% /note %}}
### Contexted `.Scratch` vs. local `newScratch`
Since Hugo 0.43, there are two different ways of using Scratch:
#### The Page's `.Scratch`
`.Scratch` is available as a Page method or a Shortcode method and attaches the "scratched" data to the given page. Either a Page or a Shortcode context is required to use `.Scratch`.
```go-html-template
{{ .Scratch.Set "greeting" "bonjour" }}
{{ range .Pages }}
{{ .Scratch.Set "greeting" (print "bonjour" .Title) }}
{{ end }}
```
#### The local `newScratch`
A Scratch instance can also be assigned to any variable using the `newScratch` function. In this case, no Page or Shortcode context is required and the scope of the scratch is only local. The methods detailed below are available from the variable the Scratch instance was assigned to.
```go-html-template
{{ $data := newScratch }}
{{ $data.Set "greeting" "hola" }}
```
### Methods
A Scratch has the following methods:
{{% note %}}
Note that the following examples assume a [local Scratch instance](#the-local-newscratch) has been stored in `$scratch`.
{{% /note %}}
#### .Set
Set the value of a given key.
```go-html-template
{{ $scratch.Set "greeting" "Hello" }}
```
#### .Get
Get the value of a given key.
```go-html-template
{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Get "greeting" }} > Hello
```
#### .Add
Add 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](/functions/collections/append/) to that list.
```go-html-template
{{ $scratch.Add "greetings" "Hello" }}
{{ $scratch.Add "greetings" "Welcome" }}
----
{{ $scratch.Get "greetings" }} > HelloWelcome
```
```go-html-template
{{ $scratch.Add "total" 3 }}
{{ $scratch.Add "total" 7 }}
----
{{ $scratch.Get "total" }} > 10
```
```go-html-template
{{ $scratch.Add "greetings" (slice "Hello") }}
{{ $scratch.Add "greetings" (slice "Welcome" "Cheers") }}
----
{{ $scratch.Get "greetings" }} > []interface {}{"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
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.Get "greetings" }} > map[french:Bonjour english:Hello]
```
#### .DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ .Scratch.SetInMap "greetings" "english" "Hello" }}
{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ .Scratch.DeleteInMap "greetings" "english" }}
----
{{ .Scratch.Get "greetings" }} > map[french:Bonjour]
```
#### .GetSortedMapValues
Return an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ $scratch.SetInMap "greetings" "english" "Hello" }}
{{ $scratch.SetInMap "greetings" "french" "Bonjour" }}
----
{{ $scratch.GetSortedMapValues "greetings" }} > [Hello Bonjour]
```
#### .Delete
Remove the given key.
```go-html-template
{{ $scratch.Set "greeting" "Hello" }}
----
{{ $scratch.Delete "greeting" }}
```
#### .Values
Return the raw backing map. Note that you should only use this method on the locally scoped Scratch instances you obtain via [`newScratch`](#the-local-newscratch), not `.Page.Scratch` etc., as that will lead to concurrency issues.
[pagevars]: /variables/page/

View File

@@ -1,111 +0,0 @@
---
title: .Store
description: Returns a Scratch that is not reset on server rebuilds.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType:
signatures: []
relatedFunctions:
- .Store
- .Scratch
---
The `.Store` method on `.Page` returns a [Scratch] to store and manipulate data. In contrast to the `.Scratch` method, this Scratch is not reset on server rebuilds.
[Scratch]: /functions/scratch/
### Methods
#### .Set
Sets the value of a given key.
```go-html-template
{{ .Store.Set "greeting" "Hello" }}
```
#### .Get
Gets the value of a given key.
```go-html-template
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.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
{{ .Store.Add "greetings" "Hello" }}
{{ .Store.Add "greetings" "Welcome" }}
{{ .Store.Get "greetings" }} → HelloWelcome
```
```go-html-template
{{ .Store.Add "total" 3 }}
{{ .Store.Add "total" 7 }}
{{ .Store.Get "total" }} → 10
```
```go-html-template
{{ .Store.Add "greetings" (slice "Hello") }}
{{ .Store.Add "greetings" (slice "Welcome" "Cheers") }}
{{ .Store.Get "greetings" }} → []interface {}{"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
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.Get "greetings" }} → map[french:Bonjour english:Hello]
```
#### .DeleteInMap
Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`.
```go-html-template
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.DeleteInMap "greetings" "english" }}
{{ .Store.Get "greetings" }} → map[french:Bonjour]
```
#### .GetSortedMapValues
Returns an array of values from `key` sorted by `mapKey`.
```go-html-template
{{ .Store.SetInMap "greetings" "english" "Hello" }}
{{ .Store.SetInMap "greetings" "french" "Bonjour" }}
{{ .Store.GetSortedMapValues "greetings" }} → [Hello Bonjour]
```
#### .Delete
Removes the given key.
```go-html-template
{{ .Store.Set "greeting" "Hello" }}
{{ .Store.Delete "greeting" }}
```

View File

@@ -1,36 +0,0 @@
---
title: .Unix
description: Converts a time.Time value to the number of seconds elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00&nbsp;UTC on 1 January 1970.
categories: [functions]
menu:
docs:
parent: functions
function:
aliases: []
returnType: int64
signatures:
- .Unix
- .UnixMilli
- .UnixMicro
- .UnixNano
relatedFunctions: []
---
The `Milli`, `Micro`, and `Nano` variants return the number of milliseconds, microseconds, and nanoseconds (respectively) elapsed since the Unix epoch.
```go-html-template
.Date.Unix → 1637259694
.ExpiryDate.Unix → 1672559999
.Lastmod.Unix → 1637361786
.PublishDate.Unix → 1637421261
("1970-01-01T00:00:00-00:00" | time.AsTime).Unix → 0
("1970-01-01T00:00:42-00:00" | time.AsTime).Unix → 42
("1970-04-11T01:48:29-08:00" | time.AsTime).Unix → 8675309
("2026-05-02T20:09:31-07:00" | time.AsTime).Unix → 1777777771
now.Unix → 1637447841
now.UnixMilli → 1637447841347
now.UnixMicro → 1637447841347378
now.UnixNano → 1637447841347378799
```

View File

@@ -0,0 +1,13 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
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,23 @@
---
# Do not remove front matter.
---
Path|Pattern|Match
:--|:--|:--
`images/foo/a.jpg`|`images/foo/*.jpg`|`true`
`images/foo/a.jpg`|`images/foo/*.*`|`true`
`images/foo/a.jpg`|`images/foo/*`|`true`
`images/foo/a.jpg`|`images/*/*.jpg`|`true`
`images/foo/a.jpg`|`images/*/*.*`|`true`
`images/foo/a.jpg`|`images/*/*`|`true`
`images/foo/a.jpg`|`*/*/*.jpg`|`true`
`images/foo/a.jpg`|`*/*/*.*`|`true`
`images/foo/a.jpg`|`*/*/*`|`true`
`images/foo/a.jpg`|`**/*.jpg`|`true`
`images/foo/a.jpg`|`**/*.*`|`true`
`images/foo/a.jpg`|`**/*`|`true`
`images/foo/a.jpg`|`**`|`true`
`images/foo/a.jpg`|`*/*.jpg`|`false`
`images/foo/a.jpg`|`*.jpg`|`false`
`images/foo/a.jpg`|`*.*`|`false`
`images/foo/a.jpg`|`*`|`false`

View File

@@ -1,3 +0,0 @@
See Go's [text/template] documentation for more details.
[text/template]: https://pkg.go.dev/text/template

View File

@@ -1,3 +0,0 @@
+++
headless = true
+++

View File

@@ -1,3 +1,10 @@
---
# Do not remove front matter.
---
{{% note %}}
Localization of dates, currencies, numbers, and percentages is performed by the [gohugoio/locales] package. The language tag of the current site must match one of the listed locales.
[gohugoio/locales]: https://github.com/gohugoio/locales
{{% /note %}}

View File

@@ -1,3 +1,7 @@
---
# Do not remove front matter.
---
When specifying the regular expression, use a raw [string literal] (backticks) instead of an interpreted string literal (double quotes) to simplify the syntax. With an interpreted string literal you must escape backslashes.
Go's regular expression package implements the [RE2 syntax]. The RE2 syntax is a subset of that accepted by [PCRE], roughly speaking, and with various [caveats]. Note that the RE2 `\C` escape sequence is not supported.

View File

@@ -1,12 +1,16 @@
---
# Do not remove front matter.
---
Format a `time.Time` value based on [Go's reference time]:
[Go's reference time]: https://pkg.go.dev/time#pkg-constants
```text {copy=false}
```text
Mon Jan 2 15:04:05 MST 2006
```
Create a format string using these components:
Create a layout string using these components:
Description|Valid components
:--|:--
@@ -21,7 +25,7 @@ Second|`"5" "05"`
AM/PM mark|`"PM"`
Time zone offsets|`"-0700" "-07:00" "-07" "-070000" "-07:00:00"`
Replace the sign in the format string with a Z to print Z instead of an offset for the UTC zone.
Replace the sign in the layout string with a Z to print Z instead of an offset for the UTC zone.
Description|Valid components
:--|:--

View File

@@ -1,7 +1,8 @@
---
title: Functions
linkTitle: Overview
description: Comprehensive list of Hugo templating functions, including basic and advanced usage examples.
description: A list of Hugo template functions including examples.
categories: []
keywords: []
menu:
docs:
@@ -9,9 +10,8 @@ menu:
parent: functions
weight: 10
weight: 10
showSectionMenu: true
aliases: [/layout/functions/,/templates/functions]
---
Go templates are lightweight but extensible. Go itself supplies built-in functions, including comparison operators and other basic tools. These are listed in the [Go template documentation][gofuncs]. Hugo has added additional functions to the basic template logic.
[gofuncs]: https://golang.org/pkg/text/template/#hdr-Functions
Use these functions within your templates and archetypes.

View File

@@ -1,20 +1,15 @@
---
title: cast.ToFloat
linkTitle: float
description: Casts a value to a decimal (base 10) floating point value.
categories: [functions]
description: Converts a value to a decimal floating-point number (base 10).
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [float]
related:
- functions/cast/ToInt
- functions/cast/ToString
returnType: float64
signatures: [cast.ToFloat INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
aliases: [/functions/float]
---

View File

@@ -1,20 +1,14 @@
---
title: cast.ToInt
linkTitle: int
description: Casts a value to a decimal (base 10) integer.
categories: [functions]
description: Converts a value to a decimal integer (base 10).
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [int]
related:
- functions/cast/ToFloat
- functions/cast/ToString
returnType: int
signatures: [cast.ToInt INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
signatures: [cast/ToInt INPUT]
aliases: [/functions/int]
---
@@ -55,5 +49,5 @@ With a hexadecimal (base 16) input:
{{% note %}}
Values with a leading zero are octal (base 8). When casting a string representation of a decimal (base 10) number, remove leading zeros:
`{{ strings.TrimLeft "0" "0011" | int }} → 11`
`{{ strings/TrimLeft "0" "0011" | int }} → 11`
{{% /note %}}

View File

@@ -1,20 +1,15 @@
---
title: cast.ToString
linkTitle: string
description: Cast a value to a string.
categories: [functions]
description: Converts a value to a string.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [string]
related:
- functions/cast/ToFloat
- functions/cast/ToInt
returnType: string
signatures: [cast.ToString INPUT]
relatedFunctions:
- cast.ToFloat
- cast.ToInt
- cast.ToString
aliases: [/functions/string]
---

View File

@@ -0,0 +1,12 @@
---
title: Cast functions
linkTitle: cast
description: Template functions to cast a value from one data type to another.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to cast a value from one data type to another.

View File

@@ -1,20 +1,15 @@
---
title: collections.After
linkTitle: after
description: Slices an array to the items after the Nth item.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [after]
related:
- functions/collections/First
- functions/collections/Last
returnType: any
signatures: [collections.After INDEX COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
aliases: [/functions/after]
---
@@ -22,10 +17,20 @@ The following shows `after` being used in conjunction with the [`slice`]function
```go-html-template
{{ $data := slice "one" "two" "three" "four" }}
{{ range after 2 $data }}
{{ . }}
{{ end }}
→ ["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
@@ -35,32 +40,32 @@ You can use `after` in combination with the [`first`] function and Hugo's [power
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" >}}
{{< 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="{{ .Permalink }}">{{ .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="{{ .Permalink }}">{{ .Title }}</a></h3>
</header>
<p>{{ .Description }}</p>
</section>
<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 }}
</div>
</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/#order-content
[lists]: /templates/lists/#sort-content
[`slice`]: /functions/collections/slice/

View File

@@ -1,22 +1,17 @@
---
title: collections.Append
linkTitle: append
description: Appends one or more elements to a slice and returns the resulting slice.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [append]
related:
- functions/collections/Merge
- functions/collections/Slice
returnType: any
signatures:
- COLLECTION | collections.Append ELEMENT [ELEMENT]...
- COLLECTION | collections.Append COLLECTION
relatedFunctions:
- collections.Append
- collections.Merge
- collections.Slice
- collections.Append ELEMENT [ELEMENT...] COLLECTION
- collections.Append COLLECTION1 COLLECTION2
aliases: [/functions/append]
---

View File

@@ -1,18 +1,13 @@
---
title: collections.Apply
linkTitle: apply
description: Returns a new collection with each element transformed by the given function.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [apply]
returnType: '[]any'
signatures: [collections.Apply COLLECTION FUNCTION PARAM...]
relatedFunctions:
- collections.Apply
- collections.Delimit
- collections.In
- collections.Reverse
@@ -25,7 +20,6 @@ The `apply` function takes three or more arguments, depending on the function be
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" }}

View File

@@ -1,21 +1,16 @@
---
title: collections.Complement
linkTitle: complement
description: Returns the elements of the last collection that are not in any of the others.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [complement]
related:
- functions/collections/Intersect
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: ['collections.Complement COLLECTION [COLLECTION]...']
relatedFunctions:
- collections.Complement
- collections.Intersect
- collections.SymDiff
- collections.Union
signatures: ['collections.Complement COLLECTION [COLLECTION...]']
aliases: [/functions/complement]
---
@@ -35,7 +30,6 @@ 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]
```
@@ -65,7 +59,7 @@ To list everything except blog articles (`blog`) and frequently asked questions
Although the example above demonstrates the `complement` function, you could use the [`where`] function as well:
[`where`]: /functions/collections/where
{{% /note %}}
{{% /note %}}
```go-html-template
{{ range where site.RegularPages "Type" "not in" (slice "blog" "faqs") }}

View File

@@ -1,24 +1,19 @@
---
title: collections.Delimit
linkTitle: delimit
description: Loops through any array, slice, or map and returns a string of all the values separated by a delimiter.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [delimit]
returnType: template.HTML
related:
- functions/collections/Apply
- functions/collections/In
- functions/collections/Reverse
- functions/collections/Seq
- functions/collections/Slice
- functions/strings/Split
returnType: string
signatures: ['collections.Delimit COLLECTION DELIMITER [LAST]']
relatedFunctions:
- collections.Apply
- collections.Delimit
- collections.In
- collections.Reverse
- collections.Seq
- collections.Slice
- strings.Split
aliases: [/functions/delimit]
---
@@ -26,8 +21,8 @@ Delimit a slice:
```go-html-template
{{ $s := slice "b" "a" "c" }}
{{ delimit $s ", " }} → "b, a, c"
{{ delimit $s ", " " and "}} → "b, a and c"
{{ delimit $s ", " }} → b, a, c
{{ delimit $s ", " " and "}} → b, a and c
```
Delimit a map:
@@ -38,6 +33,6 @@ The `delimit` function sorts maps by key, returning the values.
```go-html-template
{{ $m := dict "b" 2 "a" 1 "c" 3 }}
{{ delimit $m ", " }} → "1, 2, 3"
{{ delimit $m ", " " and "}} → "1, 2 and 3"
{{ delimit $m ", " }} → 1, 2, 3
{{ delimit $m ", " " and "}} → 1, 2 and 3
```

View File

@@ -1,40 +1,59 @@
---
title: collections.Dictionary
linkTitle: dict
description: Creates a map from a list of key and value pairs.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [dict]
related:
- functions/collections/Group
- functions/collections/IndexFunction
- functions/collections/IsSet
- functions/collections/Where
returnType: mapany
signatures: ['collections.Dictionary KEY VALUE [KEY VALUE]...']
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
signatures: ['collections.Dictionary KEY VALUE [VALUE...]']
aliases: [/functions/dict]
---
`dict` is especially useful for passing more than one value to a partial template.
```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-text-template
```go-html-template
{{ $m := dict (slice "a" "b" "c") "value" }}
```
## Example: using `dict` to pass multiple values to a `partial`
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" >}}
{{< 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>
@@ -45,7 +64,7 @@ fill="{{ .fill }}" width="{{ .width }}" height="{{ .height }}" viewBox="0 0 32 3
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" >}}
{{< code file=layouts/_default/list.html >}}
{{ partial "svgs/external-links.svg" (dict "fill" "#01589B" "width" 10 "height" 20 ) }}
{{< /code >}}

View File

@@ -1,40 +0,0 @@
---
title: collections.EchoParam
linkTitle: echoParam
description: Prints a parameter if it is set.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: [echoParam]
returnType: any
signatures: [collections.EchoParam COLLECTION KEY]
relatedFunctions: []
aliases: [/functions/echoparam]
---
For example, consider this site configuration:
{{< code-toggle file=hugo copy=false >}}
[params.footer]
poweredBy = 'Hugo'
{{< /code-toggle >}}
To print the value of `poweredBy`:
```go-html-template
{{ echoParam site.Params.footer "poweredby" }} → Hugo
```
{{% note %}}
When using the `echoParam` function you must reference the key using lower case. See the previous example.
The `echoParam` function will be deprecated in a future release. Instead, use either of the constructs below.
{{% /note %}}
```go-html-template
{{ site.Params.footer.poweredBy }} → Hugo
{{ index site.Params.footer "poweredBy" }} → Hugo
```

View File

@@ -1,53 +1,36 @@
---
title: collections.First
linkTitle: first
description: Slices an array to the first N elements.
categories: [functions]
description: Returns the given collection, limited to the first N elements.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [first]
related:
- functions/collections/After
- functions/collections/Last
returnType: any
signatures: [collections.First LIMIT COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
signatures: [collections.First N COLLECTION]
aliases: [/functions/first]
---
`first` works in a similar manner to the [`limit` keyword in
SQL][limitkeyword]. It reduces the array to only the `first N`
elements. It takes the array and number of elements as input.
`first` takes two arguments:
1. `number of elements`
2. `array` *or* `slice of maps or structs`
{{< code file="layout/_default/section.html" >}}
{{ range first 10 .Pages }}
{{ .Render "summary" }}
```go-html-template
{{ range first 5 .Pages }}
{{ .Render "summary" }}
{{ end }}
{{< /code >}}
```
*Note: Exclusive to `first`, LIMIT can be '0' to return an empty array.*
Set `N` to zero to return an empty collection.
## `first` and `where` Together
```go-html-template
{{ $emptyPageCollection := first 0 .Pages}}
```
Using `first` and [`where`] together can be very
powerful. Below snippet gets a list of posts only from [main
sections], sorts it by the `title` parameter, and then
ranges through only the first 5 posts in that list:
Use `first` and [`where`] together.
{{< code file="first-and-where-together.html" >}}
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections).ByTitle }}
{{ .Content }}
```go-html-template
{{ range where .Pages "Section" "articles" | first 5 }}
{{ .Render "summary" }}
{{ end }}
{{< /code >}}
```
[limitkeyword]: https://www.techonthenet.com/sql/select_limit.php
[`where`]: /functions/collections/where
[main sections]: /functions/collections/where#mainsections

View File

@@ -1,26 +1,21 @@
---
title: collections.Group
linkTitle: group
description: Groups a list of pages.
categories: [functions]
description: Groups the given page collection by the given key.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [group]
related:
- functions/collections/Dictionary
- functions/collections/IndexFunction
- functions/collections/IsSet
- functions/collections/Where
returnType: any
signatures: [PAGES | collections.Group KEY]
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
signatures: [collections.Group KEY PAGES]
aliases: [/functions/group]
---
{{< code file="layouts/partials/groups.html" >}}
```go-html-template
{{ $new := .Site.RegularPages | first 10 | group "New" }}
{{ $old := .Site.RegularPages | last 10 | group "Old" }}
{{ $groups := slice $new $old }}
@@ -29,12 +24,12 @@ aliases: [/functions/group]
<ul>
{{ range .Pages }}
<li>
<a href="{{ .Permalink }}">{{ .Title }}</a>
<a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
<div class="meta">{{ .Date.Format "Mon, Jan 2, 2006" }}</div>
</li>
{{ end }}
</ul>
{{ end }}
{{< /code >}}
```
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,21 +1,27 @@
---
title: collections.In
linkTitle: in
description: Reports whether an element is in an array or slice, or if a substring is in a string.
description: Reports whether the given value is a member of the given set.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [in]
related:
- functions/collections/Slice
- functions/strings/Contains
- functions/strings/ContainsAny
- functions/strings/ContainsNonSpace
- functions/strings/HasPrefix
- functions/strings/HasSuffix
returnType: bool
signatures: [collections.In SET ITEM]
relatedFunctions:
- collections.Slice
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" }}

View File

@@ -1,71 +1,66 @@
---
title: collections.Index
linkTitle: index
description: Looks up the index(es) or key(s) of the data structure passed into it.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [index]
related:
- functions/collections/Dictionary
- functions/collections/Group
- functions/collections/IsSet
- functions/collections/Where
returnType: any
signatures:
- collections.Index COLLECTION INDEXES
- collections.Index COLLECTION KEYS
relatedFunctions:
- collections.Dictionary
- collections.EchoParam
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
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-text-template
```go-html-template
{{ $slice := slice "a" "b" "c" }}
{{ index $slice 1 }} => b
{{ index $slice 0 }} → a
{{ index $slice 1 }} → b
{{ $map := dict "a" 100 "b" 200 }}
{{ index $map "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-text-template
```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $map "c" 1 }} => 20
{{ index $map "c" 1 }} 20
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $map "c" "e" }} => 20
{{ index $map "c" "e" }} 20
```
You may write multiple indices as a slice:
```go-text-template
```go-html-template
{{ $map := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $slice := slice "c" "e" }}
{{ index $map $slice }} => 20
{{ 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:
```
.
└── data
└── locations
├── abilene.toml
├── chicago.toml
├── oslo.toml
└── provo.toml
```text
data/
└── locations/
├── abilene.toml
├── chicago.toml
├── oslo.toml
└── provo.toml
```
Here is an example:
{{< code-toggle file="data/locations/oslo" copy=false >}}
{{< code-toggle file=data/locations/oslo >}}
website = "https://www.oslo.kommune.no"
pop_city = 658390
pop_metro = 1717900
@@ -73,7 +68,7 @@ pop_metro = 1717900
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 copy=false >}}
{{< code-toggle file=content/articles/oslo.md fm=true >}}
title = "My Norwegian Vacation"
location = "oslo"
{{< /code-toggle >}}

View File

@@ -1,26 +1,20 @@
---
title: collections.Intersect
linkTitle: intersect
description: Returns the common elements of two arrays or slices, in the same order as the first array.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [intersect]
related:
- functions/collections/Complement
- functions/collections/SymDiff
- functions/collections/Union
returnType: any
signatures: [collections.Intersect SET1 SET2]
relatedFunctions:
- collections.Complement
- collections.Intersect
- collections.SymDiff
- collections.Union
aliases: [/functions/intersect]
---
A useful example is to use it as `AND` filters when combined with where:
## AND filter in where query
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") }}
@@ -32,6 +26,5 @@ The above fetches regular pages not of `page` or `about` type unless they are pi
See [union](/functions/collections/union) for `OR`.
[partials]: /templates/partials/
[single]: /templates/single-page-templates/

View File

@@ -1,28 +1,25 @@
---
title: collections.IsSet
linkTitle: isset
description: Reports whether the key exists within the collection.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [isset]
related:
- functions/collections/Dictionary
- functions/collections/Group
- functions/collections/IndexFunction
- functions/collections/Where
- functions/go-template/if
- functions/go-template/with
returnType: bool
signatures: [collections.IsSet COLLECTION KEY]
relatedFunctions:
- collections.Dictionary
- collections.Group
- collections.Index
- collections.IsSet
- collections.Where
aliases: [/functions/isset]
---
For example, consider this site configuration:
{{< code-toggle file=hugo copy=false >}}
{{< code-toggle file=hugo >}}
[params]
showHeroImage = false
{{< /code-toggle >}}

View File

@@ -1,21 +1,20 @@
---
title: collections.KeyVals
linkTitle: keyVals
description: Returns a KeyVals struct.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [keyVals]
returnType: KeyValues
related:
- methods/pages/Related
returnType: types.KeyValues
signatures: [collections.KeyVals KEY VALUES...]
relatedFunctions: []
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 `Page` object.
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).
@@ -39,7 +38,6 @@ The resulting data structure is:
To extract the key and values:
```go-html-template
{{ $kv.Key }} → foo
{{ $kv.Values }} → [a b c]
```

View File

@@ -1,20 +1,15 @@
---
title: collections.Last
linkTitle: last
description: Slices an array to the last N elements.
categories: [functions]
description: Returns the given collection, limited to the last N elements.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [last]
related:
- functions/collections/After
- functions/collections/First
returnType: any
signatures: [collections.Last INDEX COLLECTION]
relatedFunctions:
- collections.After
- collections.First
- collections.Last
signatures: [collections.Last N COLLECTION]
aliases: [/functions/last]
---
@@ -23,3 +18,17 @@ aliases: [/functions/last]
{{ .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,19 +1,14 @@
---
title: collections.Merge
linkTitle: merge
description: Returns the result of merging two or more maps.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [merge]
related:
- functions/collections/Append
returnType: any
signatures: [collections.Merge MAP MAP...]
relatedFunctions:
- collections.Append
- collections.Merge
aliases: [/functions/merge]
---

View File

@@ -1,22 +1,115 @@
---
title: collections.NewScratch
linkTitle: newScratch
description: Creates a new Scratch which can be used to store values in a thread safe way.
categories: [functions]
description: Returns a locally scoped "scratch pad" to store and manipulate data.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [newScratch]
returnType: Scratch
related:
- methods/page/scratch
- methods/page/store
returnType: maps.Scratch
signatures: [collections.NewScratch ]
relatedFunctions: []
---
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
{{ $scratch := newScratch }}
{{ $scratch.Add "b" 2 }}
{{ $scratch.Add "b" 2 }}
{{ $scratch.Get "b" }} → 4
{{ $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,19 +1,15 @@
---
title: collections.Querify
linkTitle: querify
description: Takes a set or slice of key-value pairs and returns a query string to be appended to URLs.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [querify]
returnType: string
signatures:
- collections.Querify KEY VALUE [KEY VALUE]...
- collections.Querify VALUE [VALUE...]
- collections.Querify COLLECTION
relatedFunctions:
related:
- collections.Querify
- urlquery
aliases: [/functions/querify]

View File

@@ -1,16 +1,13 @@
---
title: collections.Reverse
description: Reverses the order of a collection.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: []
returnType: any
signatures: [collections.Reverse COLLECTION]
relatedFunctions:
related:
- collections.Apply
- collections.Delimit
- collections.In
@@ -20,7 +17,6 @@ relatedFunctions:
aliases: [/functions/collections.reverse]
---
```go-html-template
{{ slice 2 1 3 | collections.Reverse }} → [3 1 2]
```

View File

@@ -1,20 +1,16 @@
---
title: collections.Seq
linkTitle: seq
description: Returns a slice of integers.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [seq]
returnType: '[]int'
signatures:
- collections.Seq LAST
- collections.Seq FIRST LAST
- collections.Seq FIRST INCREMENT LAST
relatedFunctions:
related:
- collections.Apply
- collections.Delimit
- collections.In
@@ -40,3 +36,11 @@ Iterate over a sequence of integers:
{{ end }}
{{ $product }} → 24
```
The example above is contrived. To calculate the product of 2 or more numbers, use the [`math.Product`] function:
```go-html-template
{{ math.Product (seq 4) }} → 24
```
[`math.Product`]: /functions/math/product

View File

@@ -1,18 +1,13 @@
---
title: collections.Shuffle
linkTitle: shuffle
description: Returns a random permutation of a given array or slice.
keywords: [ordering]
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [shuffle]
returnType: any
signatures: [collections.Shuffle COLLECTION]
relatedFunctions:
related:
- collections.Reverse
- collections.Shuffle
- collections.Sort

View File

@@ -1,17 +1,13 @@
---
title: collections.Slice
linkTitle: slice
description: Creates a slice (array) of all passed arguments.
categories: [functions]
description: Creates a slice of all passed arguments.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [slice]
returnType: any
signatures: [collections.Slice ITEM...]
relatedFunctions:
related:
- collections.Append
- collections.Apply
- collections.Delimit
@@ -22,8 +18,6 @@ relatedFunctions:
aliases: [/functions/slice]
---
One use case is the concatenation of elements in combination with the [`delimit` function]:
```go-html-template
{{ $s := slice "a" "b" "c" }}
{{ $s }} → [a b c]

View File

@@ -1,17 +1,13 @@
---
title: collections.Sort
linkTitle: sort
description: Sorts slices, maps, and page collections.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [sort]
returnType: any
signatures: ['collections.Sort COLLECTION [KEY] [ORDER]']
relatedFunctions:
related:
- collections.Reverse
- collections.Shuffle
- collections.Sort
@@ -27,7 +23,7 @@ The `ORDER` may be either `asc` (ascending) or `desc` (descending). The default
The examples below assume this site configuration:
{{< code-toggle file="hugo" copy=false >}}
{{< code-toggle file=hugo >}}
[params]
grades = ['b','a','c']
{{< /code-toggle >}}
@@ -36,10 +32,10 @@ grades = ['b','a','c']
Sort slice elements in ascending order using either of these constructs:
{{< code file="layouts/_default/single.html" copy=false >}}
```go-html-template
{{ sort site.Params.grades }} → [a b c]
{{ sort site.Params.grades "value" "asc" }} → [a b c]
{{< /code >}}
```
In the examples above, `value` is the `KEY` representing the value of the slice element.
@@ -47,9 +43,9 @@ In the examples above, `value` is the `KEY` representing the value of the slice
Sort slice elements in descending order:
{{< code file="layouts/_default/single.html" copy=false >}}
```go-html-template
{{ sort site.Params.grades "value" "desc" }} → [c b a]
{{< /code >}}
```
In the example above, `value` is the `KEY` representing the value of the slice element.
@@ -57,7 +53,7 @@ In the example above, `value` is the `KEY` representing the value of the slice e
The examples below assume this site configuration:
{{< code-toggle file="hugo" copy=false >}}
{{< code-toggle file=hugo >}}
[params.authors.a]
firstName = "Marius"
lastName = "Pontmercy"
@@ -77,7 +73,7 @@ When sorting maps, the `KEY` argument must be lowercase.
Sort map objects in ascending order using either of these constructs:
{{< code file="layouts/_default/single.html" copy=false >}}
```go-html-template
{{ range sort site.Params.authors "firstname" }}
{{ .firstName }}
{{ end }}
@@ -85,7 +81,7 @@ Sort map objects in ascending order using either of these constructs:
{{ range sort site.Params.authors "firstname" "asc" }}
{{ .firstName }}
{{ end }}
{{< /code >}}
```
These produce:
@@ -97,11 +93,11 @@ Jean Marius Victor
Sort map objects in descending order:
{{< code file="layouts/_default/single.html" copy=false >}}
```go-html-template
{{ range sort site.Params.authors "firstname" "desc" }}
{{ .firstName }}
{{ end }}
{{< /code >}}
```
This produces:
@@ -111,25 +107,16 @@ Victor Marius Jean
## Sort a page collection
Although you can use the `sort` function to sort a page collection, Hugo provides [built-in methods for sorting page collections] by:
{{% note %}}
Although you can use the `sort` function to sort a page collection, Hugo provides [sorting and grouping methods] as well.
- weight
- linktitle
- title
- front matter parameter
- date
- expiration date
- last modified date
- publish date
- length
[sorting and grouping methods]: /methods/pages
{{% /note %}}
In this contrived example, sort the site's regular pages by `.Type` in descending order:
{{< code file="layouts/_default/home.html" copy=false >}}
```go-html-template
{{ range sort site.RegularPages "Type" "desc" }}
<h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{< /code >}}
[built-in methods for sorting page collections]: /templates/lists/#order-content
```

View File

@@ -1,17 +1,13 @@
---
title: collections.SymDiff
linkTitle: symdiff
description: Returns the symmetric difference of two collections.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [symdiff]
returnType: any
signatures: [COLLECTION | collections.SymDiff COLLECTION]
relatedFunctions:
related:
- collections.Complement
- collections.Intersect
- collections.SymDiff
@@ -25,4 +21,4 @@ Example:
{{ slice 1 2 3 | symdiff (slice 3 4) }} → [1 2 4]
```
Also see https://en.wikipedia.org/wiki/Symmetric_difference
Also see <https://en.wikipedia.org/wiki/Symmetric_difference>.

View File

@@ -1,17 +1,13 @@
---
title: collections.Union
linkTitle: union
description: Given two arrays or slices, returns a new array that contains the elements or objects that belong to either or both arrays/slices.
categories: [functions]
description: Given two arrays or slices, returns a new array that contains the elements that belong to either or both arrays/slices.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [union]
returnType: any
signatures: [collections.Union SET1 SET2]
relatedFunctions:
related:
- collections.Complement
- collections.Intersect
- collections.SymDiff
@@ -19,7 +15,7 @@ relatedFunctions:
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. The elements supported are strings, integers, and floats (only float64).
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) }}

View File

@@ -1,17 +1,13 @@
---
title: collections.Uniq
linkTitle: uniq
description: Takes in a slice or array and returns a slice with duplicate elements removed.
categories: [functions]
description: Returns the given collection, removing duplicate elements.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [uniq]
returnType: any
signatures: [collections.Uniq COLLECTION]
relatedFunctions:
related:
- collections.Reverse
- collections.Shuffle
- collections.Sort
@@ -19,7 +15,6 @@ relatedFunctions:
aliases: [/functions/uniq]
---
```go-html-template
{{ slice 1 3 2 1 | uniq }} → [1 3 2]
```

View File

@@ -1,17 +1,13 @@
---
title: collections.Where
linkTitle: where
description: Filters an array to only the elements containing a matching value for a given field.
categories: [functions]
description: Returns the given collection, removing elements that do not satisfy the comparison condition.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [where]
returnType: any
signatures: ['collections.Where COLLECTION KEY [OPERATOR] MATCH']
relatedFunctions:
signatures: ['collections.Where COLLECTION KEY [OPERATOR] VALUE']
related:
- collections.Dictionary
- collections.Group
- collections.Index
@@ -21,170 +17,434 @@ aliases: [/functions/where]
toc: true
---
`where` filters an array to only the elements containing a matching
value for a given field.
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:
It works in a similar manner to the [`where` keyword in
SQL][wherekeyword].
```go-html-template
{{ range where .Pages "Section" "foo" }}
{{ .Content }}
{{ end }}
```text
collections.Where COLLECTION KEY [OPERATOR] VALUE
--------------------
comparison condition
```
It can be used by dot-chaining the second argument to refer to a nested element of a value.
{{< code-toggle file="content/example.md" fm=true copy=false >}}
title: Example
series: golang
{{< /code-toggle >}}
Hugo will test for equality if you do not provide an `OPERATOR` argument. For example:
```go-html-template
{{ range where .Site.Pages "Params.series" "golang" }}
{{ .Content }}
{{ end }}
{{ $pages := where .Site.RegularPages "Section" "books" }}
{{ $books := where .Site.Data.books "genres" "suspense" }}
```
It can also be used with the logical operators `!=`, `>=`, `in`, etc. Without an operator, `where` compares a given field with a matching value equivalent to `=`.
## Arguments
The where function takes three or four arguments. The `OPERATOR` argument is optional.
COLLECTION
: (`any`) Typically a page collection or a [slice] of [maps].
[maps]: /getting-started/glossary/#map
[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
{{ range where .Pages "Section" "!=" "foo" }}
{{ .Content }}
{{ end }}
{{ $result := where .Site.RegularPages "Params.foo" "bar" }}
```
The following logical operators are available with `where`:
[chain]: /getting-started/glossary/#chain
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`
: `true` if a given field value equals a matching value
: (`bool`) Reports whether the given field value is equal to `VALUE`.
`!=`, `<>`, `ne`
: `true` if a given field value doesn't equal a matching value
: (`bool`) Reports whether the given field value is not equal to `VALUE`.
`>=`, `ge`
: `true` if a given field value is greater than or equal to a matching value
: (`bool`) Reports whether the given field value is greater than or equal to `VALUE`.
`>`, `gt`
: `true` if a given field value is greater than a matching value
: `true` Reports whether the given field value is greater than `VALUE`.
`<=`, `le`
: `true` if a given field value is lesser than or equal to a matching value
: (`bool`) Reports whether the given field value is less than or equal to `VALUE`.
`<`, `lt`
: `true` if a given field value is lesser than a matching value
: (`bool`) Reports whether the given field value is less than `VALUE`.
`in`
: `true` if a given field value is included in a matching value; a matching value must be an array or a slice
: (`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`
: `true` if a given field value isn't included in a matching value; a matching value must be an array or a slice
: (`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`
: `true` if a given field value that is a slice/array of strings or integers contains elements in common with the matching value; it follows the same rules as the [`intersect` function][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`
: `true` if a given field value matches a regular expression. Use the `like` operator to compare `string` values. Returns `false` when comparing other data types to the regular expression.
`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
## Use `where` with boolean values
When using booleans you should not put quotation marks.
```go-html-template
{{ range where .Pages "Draft" true }}
<p>{{ .Title }}</p>
{{ end }}
{{ $pages := where .Site.RegularPages "Section" "eq" "books" }}
{{ $pages := where .Site.RegularPages "Section" "ne" "books" }}
```
## Use `where` with `intersect`
## 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
{{ range where .Site.Pages "Params.tags" "intersect" .Params.tags }}
{{ if ne .Permalink $.Permalink }}
{{ .Render "summary" }}
{{ $sectionPages := where site.RegularPages "Section" "eq" "books" }}
{{ $pages := where $sectionPages "Params.price" "eq" 42 }}
{{ $pages := where $sectionPages "Params.price" "ne" 42.67 }}
{{ $pages := where $sectionPages "Params.price" "ge" 42 }}
{{ $pages := where $sectionPages "Params.price" "gt" 42.67 }}
{{ $pages := where $sectionPages "Params.price" "le" 42 }}
{{ $pages := where $sectionPages "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
{{ $sectionPages := where site.RegularPages "Section" "eq" "books" }}
{{ $pages := where $sectionPages "Params.fiction" "eq" true }}
{{ $pages := where $sectionPages "Params.fiction" "eq" false }}
{{ $pages := where $sectionPages "Params.fiction" "ne" true }}
{{ $pages := where $sectionPages "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
{{ $sectionPages := where site.RegularPages "Section" "eq" "fruit" }}
{{ $colors := slice "red" "yellow" }}
{{ $pages := where $sectionPages "Params.color" "in" $colors }}
```
To return a collection of pages where the "color" page parameter is neither "red" nor "yellow":
```go-html-template
{{ $sectionPages := where site.RegularPages "Section" "eq" "fruit" }}
{{ $colors := slice "red" "yellow" }}
{{ $pages := where $sectionPages "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
{{ $sectionPages := where site.RegularPages "Section" "eq" "books" }}
{{ $genres := slice "suspense" "romance" }}
{{ $pages := where $sectionPages "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 }}
```
You can also put the returned value of the `where` clauses into a variable:
## Nil comparison
{{< code file="where-intersect-variables.html" >}}
{{ $v1 := where .Site.Pages "Params.a" "v1" }}
{{ $v2 := where .Site.Pages "Params.b" "v2" }}
{{ $filtered := $v1 | intersect $v2 }}
{{ range $filtered }}
{{ end }}
{{< /code >}}
## Use `where` with `like`
This example matches pages where the "foo" parameter begins with "ab":
To return a collection of pages where the "color" parameter is present in front matter, compare to `nil`:
```go-html-template
{{ range where site.RegularPages "Params.foo" "like" `^ab` }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }}
```
{{% readfile file="/functions/_common/regular-expressions.md" %}}
## Use `where` with `first`
Using `first` and `where` together can be very
powerful. Below snippet gets a list of posts only from [**main
sections**](#mainsections), sorts it using the [default
ordering](/templates/lists/) for lists (i.e., `weight => date`), and
then ranges through only the first 5 posts in that list:
{{< code file="first-and-where-together.html" >}}
{{ range first 5 (where site.RegularPages "Type" "in" site.Params.mainSections) }}
{{ .Content }}
{{ end }}
{{< /code >}}
## Nest `where` clauses
You can also nest `where` clauses to drill down on lists of content by more than one parameter. The following first grabs all pages in the "blog" section and then ranges through the result of the first `where` clause and finds all pages that are *not* featured:
To return a collection of pages where the "color" parameter is not present in front matter, compare to `nil`:
```go-html-template
{{ range where (where .Pages "Section" "blog" ) "Params.featured" "!=" true }}
{{ $pages := where .Site.RegularPages "Params.color" "eq" nil }}
```
## Unset fields
In both examples above, note that `nil` is not quoted.
Filtering only works for set fields. To check whether a field is set or exists, you can use the operand `nil`.
## Nested comparison
This can be useful to filter a small amount of pages from a large pool. Instead of setting a field on all pages, you can set that field on required pages only.
Only the following operators are available for `nil`
* `=`, `==`, `eq`: True if the given field is not set.
* `!=`, `<>`, `ne`: True if the given field is set.
These are equivalent:
```go-html-template
{{ range where .Pages "Params.specialpost" "!=" nil }}
{{ .Content }}
{{ end }}
{{ $pages := where .Site.RegularPages "Type" "tutorials" }}
{{ $pages = where $pages "Params.level" "eq" "beginner" }}
```
## Portable `where` filters -- `site.Params.mainSections` {#mainsections}
**This is especially important for themes.**
To list the most relevant pages on the front page or similar, you
should use the `site.Params.mainSections` list instead of comparing
section names to hard-coded values like `"posts"` or `"post"`.
```go-html-template
{{ $pages := where site.RegularPages "Type" "in" site.Params.mainSections }}
{{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }}
```
If the user has not set this configuration parameter in their site configuration, it will default to the *section with the most pages*.
## Portable section comparison
The user can override the default:
Useful for theme authors, avoid hardcoding section names by using the `where` function with the [`MainSections`] method on a `Site` object.
{{< code-toggle file="hugo" >}}
[`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", "docs"]
mainSections = ['blog','galleries']
{{< /code-toggle >}}
[intersect]: /functions/collections/intersect
[wherekeyword]: https://www.techonthenet.com/sql/where.php
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

@@ -0,0 +1,12 @@
---
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.

View File

@@ -1,19 +1,14 @@
---
title: compare.Conditional
linkTitle: cond
description: Returns one of two arguments depending on the value of the control argument.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [cond]
related:
- functions/compare/Default
returnType: any
signatures: [compare.Conditional CONTROL ARG1 ARG2]
relatedFunctions:
- compare.Conditional
- compare.Default
aliases: [/functions/cond]
---
@@ -21,14 +16,14 @@ The CONTROL argument is a boolean value that indicates whether the function shou
```go-html-template
{{ $qty := 42 }}
{{ cond (le $qty 3) "few" "many" }} → "many"
{{ cond (le $qty 3) "few" "many" }} → many
```
The CONTROL argument must be either `true` or `false`. To cast a non-boolean value to boolean, pass it through the `not` operator twice.
```go-html-template
{{ cond (42 | not | not) "truthy" "falsy" }} → "truthy"
{{ cond ("" | not | not) "truthy" "falsy" }} → "falsy"
{{ cond (42 | not | not) "truthy" "falsy" }} → truthy
{{ cond ("" | not | not) "truthy" "falsy" }} → falsy
```
{{% note %}}
@@ -38,7 +33,6 @@ Unlike [ternary operators] in other languages, the `cond` function does not perf
[ternary operators]: https://en.wikipedia.org/wiki/Ternary_conditional_operator
{{% /note %}}
Due to the absence of short-circuit evaluation, these examples throw an error:
```go-html-template

View File

@@ -1,88 +1,48 @@
---
title: compare.Default
linkTitle: default
description: Allows setting a default value that can be returned if a first value is not set.
categories: [functions]
description: Returns the second argument if set, else the first argument.
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [default]
related:
- functions/compare/Conditional
- functions/go-template/Or
returnType: any
signatures: [compare.Default DEFAULT INPUT]
relatedFunctions:
- compare.Conditional
- compare.Default
aliases: [/functions/default]
---
`default` checks whether a given value is set and returns a default value if it is not. *Set* in this context means different things depending on the data type:
The `default` function returns the second argument if set, else the first argument.
* non-zero for numeric types and times
* non-zero length for strings, arrays, slices, and maps
* any boolean or struct value
* non-nil for any other types
{{% note %}}
When the second argument is the boolean `false` value, the `default` function returns `false`. All _other_ falsy values are considered unset.
`default` function examples reference the following content page:
{{% include "functions/go-template/_common/truthy-falsy.md" %}}
{{< code file="content/posts/default-function-example.md" >}}
---
title: Sane Defaults
seo_title:
date: 2017-02-18
font:
oldparam: The default function helps make your templating DRYer.
newparam:
---
{{< /code >}}
To set a default value based on truthiness, use the [`or`] operator instead.
`default` can be written in more than one way:
[`or`]: /functions/go-template/or
{{% /note %}}
The `default` function returns the second argument if set:
```go-html-template
{{ .Params.font | default "Roboto" }}
{{ default "Roboto" .Params.font }}
{{ default 42 1 }} → 1
{{ default 42 "foo" }} → foo
{{ default 42 (dict "k" "v") }} → map[k:v]
{{ default 42 (slice "a" "b") }} → [a b]
{{ default 42 true }} → true
<!-- As noted above, the boolean "false" is considered set -->
{{ default 42 false }} → false
```
Both of the above `default` function calls return `Roboto`.
A `default` value, however, does not need to be hard coded like the previous example. The `default` value can be a variable or pulled directly from the front matter using dot notation:
The `default` function returns the first argument if the second argument is not set:
```go-html-template
{{ $old := .Params.oldparam }}
<p>{{ .Params.newparam | default $old }}</p>
```
Which would return:
```html
<p>The default function helps make your templating DRYer.</p>
```
And then using dot notation
```go-html-template
<title>{{ .Params.seo_title | default .Title }}</title>
```
Which would return
```html
<title>Sane Defaults</title>
```
The following have equivalent return values but are far less terse. This demonstrates the utility of `default`:
Using `if`:
```go-html-template
<title>{{ if .Params.seo_title }}{{ .Params.seo_title }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults
```
Using `with`:
```go-html-template
<title>{{ with .Params.seo_title }}{{ . }}{{ else }}{{ .Title }}{{ end }}</title>
=> Sane Defaults
{{ default 42 0 }} → 42
{{ default 42 "" }} → 42
{{ default 42 dict }} → 42
{{ default 42 slice }} → 42
{{ default 42 <nil> }} → 42
```

View File

@@ -1,23 +1,18 @@
---
title: compare.Eq
linkTitle: eq
description: Returns the boolean truth of arg1 == arg2 || arg1 == arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [eq]
related:
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool
signatures: ['compare.Eq ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/eq]
---

View File

@@ -1,23 +1,18 @@
---
title: compare.Ge
linkTitle: ge
description: Returns the boolean truth of arg1 >= arg2 && arg1 >= arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [ge]
related:
- functions/compare/Eq
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool
signatures: ['compare.Ge ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/ge]
---

View File

@@ -1,23 +1,18 @@
---
title: compare.Gt
linkTitle: gt
description: Returns the boolean truth of arg1 > arg2 && arg1 > arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [gt]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Le
- functions/compare/Lt
- functions/compare/Ne
returnType: bool
signatures: ['compare.Gt ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/gt]
---

View File

@@ -1,23 +1,18 @@
---
title: compare.Le
linkTitle: le
description: Returns the boolean truth of arg1 <= arg2 && arg1 <= arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [le]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Lt
- functions/compare/Ne
returnType: bool
signatures: ['compare.Le ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/le]
---

View File

@@ -1,23 +1,18 @@
---
title: compare.Lt
linkTitle: lt
description: Returns the boolean truth of arg1 < arg2 && arg1 < arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [lt]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Ne
returnType: bool
signatures: ['compare.Lt ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/lt]
---

View File

@@ -1,23 +1,18 @@
---
title: compare.Ne
linkTitle: ne
description: Returns the boolean truth of arg1 != arg2 && arg1 != arg3.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [ne]
related:
- functions/compare/Eq
- functions/compare/Ge
- functions/compare/Gt
- functions/compare/Le
- functions/compare/Lt
returnType: bool
signatures: ['compare.Ne ARG1 ARG2 [ARG...]']
relatedFunctions:
- compare.Eq
- compare.Ge
- compare.Gt
- compare.Le
- compare.Lt
- compare.Ne
aliases: [/functions/ne]
---

View File

@@ -0,0 +1,12 @@
---
title: Compare functions
linkTitle: compare
description: Template functions to compare two or more values.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to compare two or more values.

View File

@@ -1,21 +1,17 @@
---
title: crypto.FNV32a
description: Returns the FNV (FowlerNollVo) 32 bit hash of a given string.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: []
related:
- functions/crypto/HMAC
- functions/crypto/MD5
- functions/crypto/SHA1
- functions/crypto/SHA256
returnType: int
signatures: [crypto.FNV32a STRING]
relatedFunctions:
- crypto.FNV32a
- crypto.HMAC
- crypto.MD5
- crypto.SHA1
- crypto.SHA256
aliases: [/functions/crypto.fnv32a]
---

View File

@@ -1,22 +1,17 @@
---
title: crypto.HMAC
linkTitle: hmac
description: Returns a cryptographic hash that uses a key to sign a message.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [hmac]
related:
- functions/crypto/FNV32a
- functions/crypto/MD5
- functions/crypto/SHA1
- functions/crypto/SHA256
returnType: string
signatures: ['crypto.HMAC HASH_TYPE KEY MESSAGE [ENCODING]']
relatedFunctions:
- crypto.FNV32a
- crypto.HMAC
- crypto.MD5
- crypto.SHA1
- crypto.SHA256
aliases: [/functions/hmac]
---

View File

@@ -1,28 +1,22 @@
---
title: crypto.MD5
linkTitle: md5
description: hashes the given input and returns its MD5 checksum.
categories: [functions]
description: Hashes the given input and returns its MD5 checksum encoded to a hexadecimal string.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [md5]
related:
- functions/crypto/FNV32a
- functions/crypto/HMAC
- functions/crypto/SHA1
- functions/crypto/SHA256
returnType: string
signatures: [crypto.MD5 INPUT]
relatedFunctions:
- crypto.FNV32a
- crypto.HMAC
- crypto.MD5
- crypto.SHA1
- crypto.SHA256
aliases: [/functions/md5]
---
```go-html-template
{{ md5 "Hello world" }} → 3e25960a79dbc69b674cd4ec67a72c62
```
This can be useful if you want to use [Gravatar](https://en.gravatar.com/) for generating a unique avatar:

View File

@@ -1,22 +1,17 @@
---
title: crypto.SHA1
linkTitle: sha1
description: Hashes the given input and returns its SHA1 checksum.
categories: [functions]
description: Hashes the given input and returns its SHA1 checksum encoded to a hexadecimal string.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [sha1]
related:
- functions/crypto/FNV32a
- functions/crypto/HMAC
- functions/crypto/MD5
- functions/crypto/SHA256
returnType: string
signatures: [crypto.SHA1 INPUT]
relatedFunctions:
- crypto.FNV32a
- crypto.HMAC
- crypto.MD5
- crypto.SHA1
- crypto.SHA256
aliases: [/functions/sha,/functions/sha1]
---

View File

@@ -1,22 +1,17 @@
---
title: crypto.SHA256
linkTitle: sha256
description: Hashes the given input and returns its SHA256 checksum.
categories: [functions]
description: Hashes the given input and returns its SHA256 checksum encoded to a hexadecimal string.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [sha256]
related:
- functions/crypto/FNV32a
- functions/crypto/HMAC
- functions/crypto/MD5
- functions/crypto/SHA1
returnType: string
signatures: [crypto.SHA256 INPUT]
relatedFunctions:
- crypto.FNV32a
- crypto.HMAC
- crypto.MD5
- crypto.SHA1
- crypto.SHA256
aliases: [/functions/sha256]
---

View File

@@ -0,0 +1,12 @@
---
title: Crypto functions
linkTitle: crypto
description: Template functions to create cryptographic hashes.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to create cryptographic hashes.

View File

@@ -1,19 +1,17 @@
---
title: data.GetCSV
linkTitle: getCSV
description: Returns an array of arrays from a local or remote CSV file, or an error if the file does not exist.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [getCSV]
returnType: '[]string'
signatures: [data.GetCSV SEPARATOR PATHPART...]
relatedFunctions:
- data.GetCSV
- data.GetJSON
related:
- functions/data/GetJSON
- functions/resources/Get
- functions/resources/GetRemote
- methods/page/Resources
returnType: '[][]string'
signatures: ['data.GetCSV SEPARATOR INPUT... [OPTIONS]']
toc: true
---
@@ -32,6 +30,12 @@ Access the data with either of the following:
{{ $data := getCSV "," "other-files/" "pets.csv" }}
```
{{% note %}}
When working with local data, the filepath is relative to the working directory.
You must not place CSV files in the project's data directory.
{{% /note %}}
Access remote data with either of the following:
```go-html-template
@@ -49,9 +53,25 @@ The resulting data structure is an array of arrays:
]
```
## Options
Add headers to the request by providing an options map:
```go-html-template
{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
```
Add multiple headers using a slice:
```go-html-template
{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
```
## Global resource alternative
Consider using `resources.Get` with [`transform.Unmarshal`] when accessing a global resource.
Consider using the [`resources.Get`] function with [`transform.Unmarshal`] when accessing a global resource.
```text
my-project/
@@ -73,7 +93,7 @@ my-project/
## Page resource alternative
Consider using `.Resources.Get` with [`transform.Unmarshal`] when accessing a page resource.
Consider using the [`Resources.Get`] method with [`transform.Unmarshal`] when accessing a page resource.
```text
my-project/
@@ -97,7 +117,7 @@ my-project/
## Remote resource alternative
Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved error handling when accessing a remote resource.
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 := "" }}
@@ -114,4 +134,7 @@ Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved e
{{ end }}
```
[`Resources.Get`]: methods/page/Resources
[`resources.GetRemote`]: /functions/resources/getremote
[`resources.Get`]: /functions/resources/get
[`transform.Unmarshal`]: /functions/transform/unmarshal

View File

@@ -1,19 +1,17 @@
---
title: data.GetJSON
linkTitle: getJSON
description: Returns a JSON object from a local or remote JSON file, or an error if the file does not exist.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [getJSON]
related:
- functions/data/GetCSV
- functions/resources/Get
- functions/resources/GetRemote
- methods/page/Resources
returnType: any
signatures: [data.GetJSON PATHPART...]
relatedFunctions:
- data.GetCSV
- data.GetJSON
signatures: ['data.GetJSON INPUT... [OPTIONS]']
toc: true
---
@@ -28,15 +26,19 @@ my-project/
Access the data with either of the following:
```go-html-template
{{ $data := getCSV "," "other-files/books.json" }}
{{ $data := getCSV "," "other-files/" "books.json" }}
{{ $data := getJSON "other-files/books.json" }}
{{ $data := getJSON "other-files/" "books.json" }}
```
{{% note %}}
When working with local data, the filepath is relative to the working directory.
{{% /note %}}
Access remote data with either of the following:
```go-html-template
{{ $data := getCSV "," "https://example.org/books.json" }}
{{ $data := getCSV "," "https://example.org/" "books.json" }}
{{ $data := getJSON "https://example.org/books.json" }}
{{ $data := getJSON "https://example.org/" "books.json" }}
```
The resulting data structure is a JSON object:
@@ -56,9 +58,25 @@ The resulting data structure is a JSON object:
]
```
## Options
Add headers to the request by providing an options map:
```go-html-template
{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getJSON "https://example.org/books.json" $opts }}
```
Add multiple headers using a slice:
```go-html-template
{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getJSON "https://example.org/books.json" $opts }}
```
## Global resource alternative
Consider using `resources.Get` with [`transform.Unmarshal`] when accessing a global resource.
Consider using the [`resources.Get`] function with [`transform.Unmarshal`] when accessing a global resource.
```text
my-project/
@@ -80,7 +98,7 @@ my-project/
## Page resource alternative
Consider using `.Resources.Get` with [`transform.Unmarshal`] when accessing a page resource.
Consider using the [`Resources.Get`] method with [`transform.Unmarshal`] when accessing a page resource.
```text
my-project/
@@ -104,7 +122,7 @@ my-project/
## Remote resource alternative
Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved error handling when accessing a remote resource.
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 := "" }}
@@ -121,4 +139,7 @@ Consider using `resources.GetRemote` with [`transform.Unmarshal`] for improved e
{{ end }}
```
[`Resources.Get`]: methods/page/Resources
[`resources.GetRemote`]: /functions/resources/getremote
[`resources.Get`]: /functions/resources/get
[`transform.Unmarshal`]: /functions/transform/unmarshal

View File

@@ -0,0 +1,12 @@
---
title: Data functions
linkTitle: data
description: Template functions to read local or remote data files.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to read local or remote data files.

View File

@@ -1,16 +1,13 @@
---
title: debug.Dump
description: Returns an object dump as a string.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: []
related: []
returnType: string
signatures: [debug.Dump VALUE]
relatedFunctions: []
---
```go-html-template
@@ -43,8 +40,6 @@ relatedFunctions: []
}
```
{{% note %}}
Output from this function may change from one release to the next. Use for debugging only.
{{% /note %}}

View File

@@ -0,0 +1,37 @@
---
title: debug.Timer
description: Creates a named timer that reports elapsed time to the console.
categories: []
keywords: []
action:
aliases: []
related: []
returnType: debug.Timer
signatures: [debug.Timer NAME]
---
{{< new-in 0.120.0 >}}
Use the `debug.Timer` function to determine execution time for a block of code, useful for finding performance bottle necks in templates.
The timer starts when you instantiate it, and stops when you call its `Stop` method.
```go-html-template
{{ $t := debug.Timer "TestSqrt" }}
{{ range seq 2000 }}
{{ $f := math.Sqrt . }}
{{ end }}
{{ $t.Stop }}
```
Use the `--logLevel info` command line flag when you build the site.
```sh
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
```

View File

@@ -0,0 +1,12 @@
---
title: Debug functions
linkTitle: debug
description: Template functions to debug your templates.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to debug your templates.

View File

@@ -0,0 +1,113 @@
---
title: diagrams.Goat
description: Converts ASCII art to an SVG diagram, returning a GoAT diagram object.
categories: []
keywords: []
action:
aliases: []
related: []
returnType: diagrams.goatDiagram
signatures: ['diagrams.Goat INPUT']
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:
[GoAT]: https://github.com/blampe/goat#readme
[render hook]: https://gohugo.io/templates/render-hooks/
Inner
: (`template.HTML`) Returns the SVG child elements without a wrapping `svg` element, allowing you to create your own wrapper.
Wrapped
: (`template.HTML`) Returns the SVG child elements wrapped in an `svg` element.
Width
: (`int`) Returns the width of the rendered diagram, in pixels.
Height
: (`int`) Returns the height of the rendered diagram, in pixels.
## GoAT Diagrams
Hugo natively supports [GoAT] diagrams.
This markdown:
````
```goat
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
```
````
Is rendered to:
```html
<div class="goat svg-container">
<svg xmlns="http://www.w3.org/2000/svg" font-family="Menlo,Lucida Console,monospace" viewBox="0 0 352 57">
...
</svg>
</div>
```
Which appears in your browser as:
```goat {class="mw6-ns"}
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
```
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
## Code block render hook
By way of example, let's create a code block render hook to render GoAT diagrams as `figure` elements with an optional caption.
{{< code file=layouts/_default/_markup/render-codeblock-goat.html >}}
{{ $caption := or .Attributes.caption "" }}
{{ $class := or .Attributes.class "diagram" }}
{{ $id := or .Attributes.id (printf "diagram-%d" (add 1 .Ordinal)) }}
<figure id="{{ $id }}">
{{ with diagrams.Goat (trim .Inner "\n\r") }}
<svg class="{{ $class }}" width="{{ .Width }}" height="{{ .Height }}" xmlns="http://www.w3.org/2000/svg" version="1.1">
{{ .Inner }}
</svg>
{{ end }}
<figcaption>{{ $caption }}</figcaption>
</figure>
{{< /code >}}
This markdown:
{{< code file=content/example.md lang=text >}}
```goat {class="foo" caption="Diagram 1: Example"}
.---. .-. .-. .-. .---.
| A +--->| 1 |<--->| 2 |<--->| 3 |<---+ B |
'---' '-' '+' '+' '---'
```
{{< /code >}}
Is rendered to:
```html
<figure id="diagram-1">
<svg class="foo" width="272" height="57" xmlns="http://www.w3.org/2000/svg" version="1.1">
...
</svg>
<figcaption>Diagram 1: Example</figcaption>
</figure>
```
Use CSS to style the SVG as needed:
```css
svg.foo {
font-family: "Segoe UI","Noto Sans",Helvetica,Arial,sans-serif
}
```

View File

@@ -0,0 +1,12 @@
---
title: Diagram functions
linkTitle: diagrams
description: Template functions to render diagrams.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to render diagrams.

View File

@@ -1,24 +1,19 @@
---
title: encoding.Base64Decode
linkTitle: base64Decode
description: Returns the base64 decoding of the given content.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [base64Decode]
related:
- functions/encoding/Base64Encode
returnType: string
signatures: [encoding.Base64Decode INPUT]
signatures:
-
- base64Decode INPUT
aliases: [/functions/base64Decode]
---
```go-html-template
{{ "SHVnbw==" | base64Decode }} → "Hugo"
{{ "SHVnbw==" | base64Decode }} → Hugo
```
Use the `base64Decode` function to decode responses from APIs. For example, the result of this call to GitHub's API contains the base64-encoded representation of the repository's README file:

View File

@@ -1,22 +1,17 @@
---
title: encoding.Base64Encode
linkTitle: base64Encode
description: Returns the base64 decoding of the given content.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [base64Encode]
related:
- functions/encoding/Base64Decode
returnType: string
signatures: [encoding.Base64Encode INPUT]
relatedFunctions:
- encoding.Base64Decode
- encoding.Base64Encode
aliases: [/functions/base64, /functions/base64Encode]
---
```go-html-template
{{ "Hugo" | base64Encode }} → "SHVnbw=="
{{ "Hugo" | base64Encode }} → SHVnbw==
```

View File

@@ -1,31 +1,24 @@
---
title: encoding.Jsonify
linkTitle: jsonify
description: Encodes a given object to JSON.
categories: [functions]
description: Encodes the given object to JSON.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [jsonify]
returnType: template.HTML
related:
- functions/transform/Remarshal
- functions/transform/Unmarshal
signatures:
- encoding.Jsonify INPUT
- encoding.Jsonify OPTIONS INPUT
relatedFunctions:
- encoding.Jsonify
- transform.Remarshal
- transform.Unmarshal
- encoding.Jsonify [OPTIONS] INPUT
aliases: [/functions/jsonify]
---
To customize the printing of the JSON, pass a map of options as the first
argument. Supported options are "prefix" and "indent". Each JSON element in
To customize the printing of the JSON, pass an options map as the first
argument. Supported options are "prefix" and "indent". Each JSON element in
the output will begin on a new line beginning with *prefix* followed by one or
more copies of *indent* according to the indentation nesting.
```go-html-template
{{ dict "title" .Title "content" .Plain | jsonify }}
{{ dict "title" .Title "content" .Plain | jsonify (dict "indent" " ") }}
@@ -34,15 +27,11 @@ more copies of *indent* according to the indentation nesting.
## Options
indent ("")
: Indentation to use.
indent
: (`string`) Indentation to use. Default is "".
prefix ("")
: Indentation prefix.
prefix
: (`string`) Indentation prefix. Default is "".
noHTMLEscape (false)
: Disable escaping of problematic HTML characters inside JSON quoted strings. The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e to avoid certain safety problems that can arise when embedding JSON in HTML.
See also the `.PlainWords`, `.Plain`, and `.RawContent` [page variables][pagevars].
[pagevars]: /variables/page/
noHTMLEscape
: (`bool`) Disable escaping of problematic HTML characters inside JSON quoted strings. The default behavior is to escape `&`, `<`, and `>` to `\u0026`, `\u003c`, and `\u003e` to avoid certain safety problems that can arise when embedding JSON in HTML. Default is `false`.

View File

@@ -0,0 +1,12 @@
---
title: Encoding functions
linkTitle: encoding
description: Template functions to encode and decode data.
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to encode and decode data.

View File

@@ -1,26 +1,21 @@
---
title: fmt.Errorf
linkTitle: errorf
description: Log an ERROR from a template.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [errorf]
related:
- functions/fmt/Erroridf
- functions/fmt/Warnf
returnType: string
signatures: ['fmt.Errorf FORMAT [INPUT]']
relatedFunctions:
- fmt.Errorf
- fmt.Erroridf
- fmt.Warnf
aliases: [/functions/errorf]
---
The documentation for [Go's fmt package] describes the structure and content of the format string.
{{% include "functions/fmt/_common/fmt-layout.md" %}}
Like the [`printf`] function, the `errorf` function evaluates the format string. It then prints the result to the ERROR log and fails the build. Hugo prints each unique message once to avoid flooding the log with duplicate errors.
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 }}
@@ -29,5 +24,3 @@ Like the [`printf`] function, the `errorf` function evaluates the format string
Use the [`erroridf`] function to allow optional suppression of specific errors.
[`erroridf`]: /functions/fmt/erroridf
[`printf`]: /functions/fmt/printf
[Go's fmt package]: https://pkg.go.dev/fmt

View File

@@ -1,28 +1,21 @@
---
title: fmt.Erroridf
linkTitle: erroridf
description: Log a suppressable ERROR from a template.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [erroridf]
related:
- functions/fmt/Errorf
- functions/fmt/Warnf
returnType: string
signatures: ['fmt.Erroridf ID FORMAT [INPUT]']
relatedFunctions:
- fmt.Errorf
- fmt.Erroridf
- fmt.Warnf
aliases: [/functions/erroridf]
---
The documentation for [Go's fmt package] describes the structure and content of the format string.
{{% include "functions/fmt/_common/fmt-layout.md" %}}
Like the [`errorf`] function, the `erroridf` function evaluates the format string, prints the result to the ERROR log, then fails the build. Hugo prints each unique message once to avoid flooding the log with duplicate errors.
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 `ignoreErrors` array in your site configuration.
This template code:
@@ -34,15 +27,14 @@ Produces this console log:
```text
ERROR You should consider fixing this.
If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site config:
ignoreErrors = ["error-42"]
You can suppress this error by adding the following to your site configuration:
ignoreErrors = ['error-42']
```
To suppress this message:
{{< code-toggle file=hugo copy=false >}}
{{< code-toggle file=hugo >}}
ignoreErrors = ["error-42"]
{{< /code-toggle >}}
[`errorf`]: /functions/fmt/errorf
[Go's fmt package]: https://pkg.go.dev/fmt

View File

@@ -1,25 +1,20 @@
---
title: fmt.Print
linkTitle: print
description: Prints the default representation of the given arguments using the standard `fmt.Print` function.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [print]
related:
- functions/fmt/Printf
- functions/fmt/Println
returnType: string
signatures: [fmt.Print INPUT]
relatedFunctions:
- fmt.Print
- fmt.Printf
- fmt.Println
aliases: [/functions/print]
---
```go-html-template
{{ print "foo" }} → "foo"
{{ print "foo" "bar" }} → "foobar"
{{ print "foo" }} → foo
{{ print "foo" "bar" }} → foobar
{{ print (slice 1 2 3) }} → [1 2 3]
```

View File

@@ -1,26 +1,19 @@
---
title: fmt.Printf
linkTitle: printf
description: Formats a string using the standard `fmt.Sprintf` function.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [printf]
related:
- functions/fmt/Print
- functions/fmt/Println
returnType: string
signatures: ['fmt.Printf FORMAT [INPUT]']
relatedFunctions:
- fmt.Print
- fmt.Printf
- fmt.Println
aliases: [/functions/printf]
---
The documentation for [Go's fmt package] describes the structure and content of the format string.
[Go's fmt package]: https://pkg.go.dev/fmt
{{% include "functions/fmt/_common/fmt-layout.md" %}}
```go-html-template
{{ $var := "world" }}

View File

@@ -1,23 +1,18 @@
---
title: fmt.Println
linkTitle: println
description: Prints the default representation of the given argument using the standard `fmt.Print` function and enforces a linebreak.
categories: [functions]
description: Prints the default representation of the given argument using the standard `fmt.Print` function and enforces a line break.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [println]
related:
- functions/fmt/Print
- functions/fmt/Printf
returnType: string
signatures: [fmt.Println INPUT]
relatedFunctions:
- fmt.Print
- fmt.Printf
- fmt.Println
aliases: [/functions/println]
---
```go-html-template
{{ println "foo" }} → "foo\n"
{{ println "foo" }} → foo\n
```

View File

@@ -1,30 +1,22 @@
---
title: fmt.Warnf
linkTitle: warnf
description: Log a WARNING from a template.
categories: [functions]
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: [warnf]
related:
- functions/fmt/Errorf
- functions/fmt/Erroridf
returnType: string
signatures: ['fmt.Warnf FORMAT [INPUT]']
relatedFunctions:
- fmt.Errorf
- fmt.Erroridf
- fmt.Warnf
aliases: [/functions/warnf]
---
The documentation for [Go's fmt package] describes the structure and content of the format string.
{{% include "functions/fmt/_common/fmt-layout.md" %}}
Like the [`printf`] function, the `warnf` function evaluates the format string. It then prints the result to the WARNING log. Hugo prints each unique message once to avoid flooding the log with duplicate warnings.
The `warnf` function evaluates the format string, then prints the result to the WARNING log. Hugo prints each unique message once to avoid flooding the log with duplicate warnings.
```go-html-template
{{ warnf "Copyright notice missing from site configuration" }}
{{ warnf "The %q shortcode was unable to find %s. See %s" .Name $file .Position }}
```
[`printf`]: /functions/fmt/printf
[Go's fmt package]: https://pkg.go.dev/fmt

View File

@@ -0,0 +1,13 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
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,7 @@
---
# Do not remove front matter.
---
The documentation for Go's [fmt] package describes the structure and content of the format string.
[fmt]: https://pkg.go.dev/fmt

View File

@@ -0,0 +1,12 @@
---
title: Fmt functions
linkTitle: fmt
description: Template functions to print strings within a template or to print messages to the terminal
categories: []
keywords: []
menu:
docs:
parent: functions
---
Use these functions to print strings within a template or to print messages to the terminal.

View File

@@ -0,0 +1,11 @@
---
title: Global functions
linkTitle: global
description: Global template functions to access page and site data.
categories: []
menu:
docs:
parent: functions
---
Use these global functions to access page and site data.

View File

@@ -1,23 +1,21 @@
---
title: page
description: Provides global access to the .Page object.
categories: [functions]
description: Provides global access to a Page object.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: []
related:
- functions/global/site
returnType:
signatures: [page]
relatedFunctions:
- hugo
- page
- site
toc: true
aliases: [/functions/page]
---
At the top level of a template that receives the `Page` object in context, these are equivalent:
{{< new-in 0.111.0 >}}
At the top level of a template that receives a `Page` object in context, these are equivalent:
```go-html-template
{{ .Params.foo }}
@@ -25,7 +23,7 @@ At the top level of a template that receives the `Page` object in context, these
{{ page.Params.foo }}
```
When the `Page` object is not in context, you can use the global `page` function:
When a `Page` object is not in context, you can use the global `page` function:
```go-html-template
{{ page.Params.foo }}
@@ -39,7 +37,7 @@ Do not use the global `page` function in shortcodes, partials called by shortcod
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.
But when you are deeply nested inside of a [content view], [partial], or [render hook], it isn't always practical or possible to access the `Page` object.
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.
Use the global `page` function to access the `Page` object from anywhere in any template.
@@ -47,7 +45,7 @@ Use the global `page` function to access the `Page` object from anywhere in any
### Be aware of top-level context
The global `page` function accesses the `Page` object passed into the top-level template.
The global `page` function accesses the `Page` object passed into the top-level template.
With this content structure:
@@ -86,9 +84,9 @@ Do not use the global `page` function in:
- Shortcodes
- Partials called by shortcodes
- Partials cached by the `partialCached` function
- Partials cached by the [`partialCached`] function
Hugo caches rendered shortcodes. If you use the `global` page function within a shortcode, and the page content is rendered in two or more templates, the cached shortcodes may be incorrect.
Hugo caches rendered shortcodes. If you use the global `page` function within a shortcode, and the page content is rendered in two or more templates, the cached shortcodes may be incorrect.
Consider this section template:
@@ -99,10 +97,12 @@ Consider this section template:
{{ end }}
```
When you call the `.Summary` method, Hugo renders the page `.Content` including shortcodes. In this case, within a shortcode, the global `page` function accesses the `Page` object of the section page, not the content page.
When you call the [`Summary`] method, Hugo renders the page content including shortcodes. In this case, within a shortcode, the global `page` function accesses the `Page` object of the section page, not the content page.
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
[content view]: /getting-started/glossary/#content-view
[partial]: /getting-started/glossary/#partial
[render hook]: /getting-started/glossary/#render-hook

View File

@@ -1,19 +1,14 @@
---
title: site
description: Provides global access to the .Site object.
categories: [functions]
description: Provides global access to the current Site object.
categories: []
keywords: []
menu:
docs:
parent: functions
function:
action:
aliases: []
related:
- functions/global/page
returnType:
signatures: [site]
relatedFunctions:
- hugo
- page
- site
aliases: [/functions/site]
---

View File

@@ -0,0 +1,13 @@
---
cascade:
_build:
list: never
publishResources: false
render: never
---
<!--
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,7 @@
---
# Do not remove front matter.
---
See Go's [text/template] documentation for more information.
[text/template]: https://pkg.go.dev/text/template

View File

@@ -0,0 +1,5 @@
---
# Do not remove front matter.
---
In Go templates, the falsy values are `false`, `0`, any nil pointer or interface value, and any array, slice, map, or string of length zero. Everything else is truthy.

View File

@@ -0,0 +1,14 @@
---
title: Go template functions, operators, and statements
linkTitle: go template
description: Template functions, operators, and statements provided by Go's text/template package.
categories: []
keywords: []
menu:
docs:
parent: functions
---
These are the functions, operators, and statements provided by Go's [text/template] package.
[text/template]: https://pkg.go.dev/text/template

View File

@@ -0,0 +1,26 @@
---
title: and
description: Returns the first falsy argument. If all arguments are truthy, returns the last argument.
categories: []
keywords: []
action:
aliases: []
related:
- functions/go-template/not
- functions/go-template/or
returnType: any
signatures: [and VALUE...]
---
{{% include "functions/go-template/_common/truthy-falsy.md" %}}
```go-html-template
{{ and 1 0 "" }} → 0 (int)
{{ and 1 false 0 }} → false (bool)
{{ and 1 2 3 }} → 3 (int)
{{ and "a" "b" "c" }} → c (string)
{{ and "a" 1 true }} → true (bool)
```
{{% include "functions/go-template/_common/text-template.md" %}}

View File

@@ -0,0 +1,55 @@
---
title: block
description: Defines a template and executes it in place.
categories: []
keywords: []
action:
aliases: []
related:
- functions/go-template/define
- functions/go-template/end
returnType:
signatures: [block NAME CONTEXT]
---
A block is shorthand for defining a template:
```go-html-template
{{ define "name" }} T1 {{ end }}
```
and then executing it in place:
```go-html-template
{{ template "name" pipeline }}
```
The typical use is to define a set of root templates that are then customized by redefining the block templates within.
{{< code file=layouts/_default/baseof.html >}}
<body>
<main>
{{ block "main" . }}
{{ print "default value if 'main' template is empty" }}
{{ end }}
</main>
</body>
{{< /code >}}
{{< code file=layouts/_default/single.html >}}
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ end }}
{{< /code >}}
{{< code file=layouts/_default/list.html >}}
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{ end }}
{{< /code >}}
{{% include "functions/go-template/_common/text-template.md" %}}

View File

@@ -0,0 +1,33 @@
---
title: break
description: Used with the range statement, stops the innermost iteration and bypasses all remaining iterations.
categories: []
keywords: []
action:
aliases: []
related:
- functions/go-template/continue
- functions/go-template/range
returnType:
signatures: [break]
---
This template code:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
{{ if eq . "bar" }}
{{ break }}
{{ end }}
<p>{{ . }}</p>
{{ end }}
```
Is rendered to:
```html
<p>foo</p>
```
{{% include "functions/go-template/_common/text-template.md" %}}

View File

@@ -0,0 +1,34 @@
---
title: continue
description: Used with the range statement, stops the innermost iteration and continues to the next iteration.
categories: []
keywords: []
action:
aliases: []
related:
- functions/go-template/break
- functions/go-template/range
returnType:
signatures: [continue]
---
This template code:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
{{ if eq . "bar" }}
{{ continue }}
{{ end }}
<p>{{ . }}</p>
{{ end }}
```
Is rendered to:
```html
<p>foo</p>
<p>baz</p>
```
{{% include "functions/go-template/_common/text-template.md" %}}

View File

@@ -0,0 +1,55 @@
---
title: define
description: Defines a template.
categories: []
keywords: []
action:
aliases: []
related:
- functions/go-template/block
- functions/go-template/end
- functions/go-template/template
- functions/partials/Include
- functions/partials/IncludeCached
returnType:
signatures: [define NAME]
---
Use with the [`block`] statement:
```go-html-template
{{ block "main" . }}
{{ print "default value if 'main' template is empty" }}
{{ end }}
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ end }}
```
Use with the [`partial`] function:
```go-html-template
{{ partial "inline/foo.html" (dict "answer" 42) }}
{{ define "partials/inline/foo.html" }}
{{ printf "The answer is %v." .answer }}
{{ end }}
```
Use with the [`template`] function:
```go-html-template
{{ template "foo" (dict "answer" 42) }}
{{ define "foo" }}
{{ printf "The answer is %v." .answer }}
{{ end }}
```
[`block`]: /functions/go-template/block
[`template`]: /functions/go-template/block
[`partial`]: /functions/partials/include/
{{% include "functions/go-template/_common/text-template.md" %}}

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