hugo-wasm/content/en/functions/collections/Where.md
Bjørn Erik Pedersen 346b60358d Squashed 'docs/' changes from 4429eeeea..73a01565c
73a01565c Remove comment shortcode documentation
0ca7ccd30 Replace usage of comment shortcode with HTML comments
fe10d9899 Remove expired new-in labels
11e89dfcb [editorial] Link to proper render-hook page in relref.md
11a581c2f netlify: Hugo 0.142.0
1a4fcf7f7 Miscellaneous edits
2c7a3165f Markdown linting and cleanup
69d7a781b Replace links to glossary terms with custom render hook syntax
441752d2d Refactor glossary lookup portion of link render hook
80109a14f Fix glossary term linking for plural form
cd95f0f34 Update link render hook to support glossary links
53eadb430 Remove the glossary template
1d40a7f3b Improve transform.ToMath examples
586970df2 Misc edits
6a06a8de7 Add glossary link shortcode
4171c0eb7 Improve description of masking with non-transparent images
41c8feb64 Fix example of image.Mask filter
704a81656 Add alignx option to images.Text usage example
7c03eb0cc Clarify context in example of using the try statement
56d9c9b71 Refactor glossary of terms
042a6846b Add expiry dates to deprecated methods pages
365ab345f Remove services key from instagram shortcode page
b7fe31e07 Reorder options list for images.Text filter
8051ff818 Format directory names, file names, and file paths as code
d09a14623 Update version refs for Hugo and Dart Sass
3bb006974 Add NODE_VERSION to Netlify config examples
3a0f2531e Fix typo
7e3198eaf Fix typo
cf56452a3 Fix typo
a9f51d13e Fix typo
82bfdd8c3 Fix typo
a5c41a053 Fix typo
abcfed7a5 Fix typo
8c1debf3a Remove outdated new-in badges
809ddf9ef Update theme
63867d56f Use warnf instead of errorf in try-catch example
dee3e5f09 Update theme
9791f7057 Remove TODO from comment shortcode examples
a346ca1fd Elevate embedded shortcode documentation to its own section
8fa19b50f hugoreleaser.toml =>  hugoreleaser.yaml
575d60345 Update docs for v0.141.0
a0a442d62 netlify: Hugo 0.141.0
6667cbcd8 Merge commit '81a7b6390036138356773c87a886679c81c524e1'
f36fc013e docs: Regen CLI docs
365a47ded tpl/images: Change signature of images.QR to images.QR TEXT OPTIONS
ae8f8af0a images.Text: Add "alignx" option for horizontal alignment
8f45ccca6 docs: Regen CLI docs
f0e6304f4 Merge commit 'e9fbadacc3f09191e2e19f112a49777eeb8df06c'
cb9bec2b2 tpl/images: Add images.QR function

git-subtree-dir: docs
git-subtree-split: 73a01565c5ba0774d65aa6f2384c44804fefa37d
2025-01-23 09:46:02 +01:00

12 KiB

title description categories keywords action toc aliases
collections.Where Returns the given collection, removing elements that do not satisfy the comparison condition.
aliases related returnType signatures
where
any
collections.Where COLLECTION KEY [OPERATOR] VALUE
true
/functions/where

The where function returns the given collection, removing elements that do not satisfy the comparison condition. The comparison condition is composed of the KEY, OPERATOR, and VALUE arguments:

collections.Where COLLECTION KEY [OPERATOR] VALUE
                             --------------------
                             comparison condition

Hugo will test for equality if you do not provide an OPERATOR argument. For example:

{{ $pages := where .Site.RegularPages "Section" "books" }}
{{ $books := where .Site.Data.books "genres" "suspense" }}

Arguments

The where function takes three or four arguments. The OPERATOR argument is optional.

COLLECTION
(any) A page collection or a slice of maps.
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:
{{ $result := where .Site.RegularPages "Params.foo" "bar" }}
OPERATOR
(string) The logical comparison operator.
VALUE
(any) The value with which to compare. The values to compare must have comparable data types. For example:
Comparison Result
"123" "eq" "123" true
"123" "eq" 123 false
false "eq" "false" false
false "eq" false true

When one or both of the values to compare is a slice, use the in, not in, or intersect operators as described below.

Operators

Use any of the following logical operators:

=, ==, eq
(bool) Reports whether the given field value is equal to VALUE.
!=, <>, ne
(bool) Reports whether the given field value is not equal to VALUE.
>=, ge
(bool) Reports whether the given field value is greater than or equal to VALUE.
>, gt
true Reports whether the given field value is greater than VALUE.
<=, le
(bool) Reports whether the given field value is less than or equal to VALUE.
<, lt
(bool) Reports whether the given field value is less than VALUE.
in
(bool) Reports whether the given field value is a member of VALUE. Compare string to slice, or string to string. See details.
not in
(bool) Reports whether the given field value is not a member of VALUE. Compare string to slice, or string to string. See details.
intersect
(bool) Reports whether the given field value (a slice) contains one or more elements in common with VALUE. See details.
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:

{{ $pages := where .Site.RegularPages "Section" "eq" "books" }}
{{ $pages := where .Site.RegularPages "Section" "ne" "books" }}

Numeric comparison

Compare the value of the given field to an int or float:

{{ $books := where site.RegularPages "Section" "eq" "books" }}

{{ $pages := where $books "Params.price" "eq" 42 }}
{{ $pages := where $books "Params.price" "ne" 42.67 }}
{{ $pages := where $books "Params.price" "ge" 42 }}
{{ $pages := where $books "Params.price" "gt" 42.67 }}
{{ $pages := where $books "Params.price" "le" 42 }}
{{ $pages := where $books "Params.price" "lt" 42.67 }}

Boolean comparison

Compare the value of the given field to a bool:

{{ $books := where site.RegularPages "Section" "eq" "books" }}

{{ $pages := where $books "Params.fiction" "eq" true }}
{{ $pages := where $books "Params.fiction" "eq" false }}
{{ $pages := where $books "Params.fiction" "ne" true }}
{{ $pages := where $books "Params.fiction" "ne" false }}

Member comparison

Compare a scalar to a slice.

For example, to return a collection of pages where the color page parameter is either "red" or "yellow":

{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}

{{ $colors := slice "red" "yellow" }}
{{ $pages := where $fruit "Params.color" "in" $colors }}

To return a collection of pages where the "color" page parameter is neither "red" nor "yellow":

{{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}

{{ $colors := slice "red" "yellow" }}
{{ $pages := where $fruit "Params.color" "not in" $colors }}

Intersection comparison

Compare a [slice] to a [slice], returning collection elements with common values. This is frequently used when comparing taxonomy terms.

For example, to return a collection of pages where any of the terms in the "genres" taxonomy are "suspense" or "romance":

{{ $books := where site.RegularPages "Section" "eq" "books" }}

{{ $genres := slice "suspense" "romance" }}
{{ $pages := where $books "Params.genres" "intersect" $genres }}

Regular expression comparison

{{< new-in 0.116.0 >}}

To return a collection of pages where the "author" page parameter begins with either "victor" or "Victor":

{{ $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.

For example, to return a collection of pages that were created before the current year:

{{ $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:

{{ $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. To be safe, filter the pages by ranging through the collection:

{{ $events := where .Site.RegularPages "Type" "events" }}
{{ $futureEvents := slice }}
{{ range $events }}
  {{ if gt (time.AsTime .Params.eventDate) now }}
    {{ $futureEvents = $futureEvents | append . }}
  {{ end }}
{{ end }}

Nil comparison

To return a collection of pages where the "color" parameter is present in front matter, compare to nil:

{{ $pages := where .Site.RegularPages "Params.color" "ne" nil }}

To return a collection of pages where the "color" parameter is not present in front matter, compare to nil:

{{ $pages := where .Site.RegularPages "Params.color" "eq" nil }}

In both examples above, note that nil is not quoted.

Nested comparison

These are equivalent:

{{ $pages := where .Site.RegularPages "Type" "tutorials" }}
{{ $pages = where $pages "Params.level" "eq" "beginner" }}
{{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }}

Portable section comparison

Useful for theme authors, avoid hardcoding section names by using the where function with the MainSections method on a Site object.

{{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }}

With this construct, a theme author can instruct users to specify their main sections in the site configuration:

{{< code-toggle file=hugo >}} [params] mainSections = ['blog','galleries'] {{< /code-toggle >}}

If params.mainSections is not defined in the site configuration, the MainSections method returns a slice with one element---the top level section with the most pages.

Boolean/undefined comparison

Consider this site content:

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:

<ul>
  {{ range where .Site.RegularPages "Params.exclude" "eq" false }}
    <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
  {{ end }}
</ul>

Is rendered to:

<ul>
  <li><a href="/posts/post-1/">Post 1</a></li>
</ul>

This template:

<ul>
  {{ range where .Site.RegularPages "Params.exclude" "eq" true }}
    <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
  {{ end }}
</ul>

Is rendered to:

<ul>  
  <li><a href="/posts/post-2/">Post 2</a></li>
</ul>

Inequality test

This template:

<ul>
  {{ range where .Site.RegularPages "Params.exclude" "ne" false }}
    <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
  {{ end }}
</ul>

Is rendered to:

<ul>
  <li><a href="/posts/post-2/">Post 2</a></li>
  <li><a href="/posts/post-3/">Post 3</a></li>
</ul>

This template:

<ul>
  {{ range where .Site.RegularPages "Params.exclude" "ne" true }}
    <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
  {{ end }}
</ul>

Is rendered to:

<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.

This 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:

<ul>
  <li><a href="/posts/post-1/">Post 1</a></li>
</ul>

This 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:

<ul>
  <li><a href="/posts/post-1/">Post 2</a></li>
</ul>