Debian Codegraph @

docs/content/en/functions/collections/Where.md

raw
1 ---
2 title: collections.Where
3 description: Returns a slice by filtering the given slice based on a key, operator, and value.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: [where]
9 returnType: '[]any'
10 signatures: ['collections.Where SLICE KEY [OPERATOR] VALUE']
11 aliases: [/functions/where]
12 ---
13
14 ## Usage
15
16 The `where` function returns the given slice, removing elements that do not satisfy the comparison condition. The comparison condition is composed of the `KEY`, `OPERATOR`, and `VALUE` arguments:
17
18 ```text
19 collections.Where SLICE KEY [OPERATOR] VALUE
20 --------------------
21 comparison condition
22 ```
23
24 Hugo will test for equality if you do not provide an `OPERATOR` argument. For example:
25
26 ```go-html-template
27 {{ $pages := where .Site.RegularPages "Section" "books" }}
28 {{ $books := where hugo.Data.books "genres" "suspense" }}
29 ```
30
31 ### Arguments
32
33 The where function takes three or four arguments. The `OPERATOR` argument is optional.
34
35 `SLICE`
36 : (`[]any`) A [page collection](g) or a [slice](g) of [maps](g).
37
38 `KEY`
39 : (`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](g) the subkey as shown below:
40
41 ```go-html-template
42 {{ $result := where .Site.RegularPages "Params.foo" "bar" }}
43 ```
44
45 `OPERATOR`
46 : (`string`) The logical comparison [operator](#operators).
47
48 `VALUE`
49 : (`any`) The value with which to compare. The values to compare must have comparable data types. For example:
50
51 Comparison|Result
52 :--|:--
53 `"123" "eq" "123"`|`true`
54 `"123" "eq" 123`|`false`
55 `false "eq" "false"`|`false`
56 `false "eq" false`|`true`
57
58 When one or both of the values to compare is a slice, use the `in`, `not in`, or `intersect` operators as described below.
59
60 ### Operators
61
62 Use any of the following logical operators:
63
64 `=`, `==`, `eq`
65 : (`bool`) Reports whether the given field value is equal to `VALUE`.
66
67 `!=`, `<>`, `ne`
68 : (`bool`) Reports whether the given field value is not equal to `VALUE`.
69
70 `>=`, `ge`
71 : (`bool`) Reports whether the given field value is greater than or equal to `VALUE`.
72
73 `>`, `gt`
74 : `true` Reports whether the given field value is greater than `VALUE`.
75
76 `<=`, `le`
77 : (`bool`) Reports whether the given field value is less than or equal to `VALUE`.
78
79 `<`, `lt`
80 : (`bool`) Reports whether the given field value is less than `VALUE`.
81
82 `in`
83 : (`bool`) Reports whether the given field value is a member of `VALUE`. Compare string to slice, or string to string.
84
85 `not in`
86 : (`bool`) Reports whether the given field value is not a member of `VALUE`. Compare string to slice, or string to string.
87
88 `intersect`
89 : (`bool`) Reports whether the given field value (a slice) contains one or more elements in common with `VALUE`.
90
91 `like`
92 : (`bool`) Reports whether the given field value matches the [regular expression](g) 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.
93
94 ## Examples
95
96 The following examples demonstrate comparisons using various operators and data types.
97
98 > [!NOTE]
99 > The examples below perform comparisons within a page collection, but the same comparisons are applicable to a slice of maps.
100
101 ### String comparison
102
103 Compare the value of the given field to a [`string`](g):
104
105 ```go-html-template
106 {{ $pages := where .Site.RegularPages "Section" "eq" "books" }}
107 {{ $pages := where .Site.RegularPages "Section" "ne" "books" }}
108 ```
109
110 ### Numeric comparison
111
112 Compare the value of the given field to an [`int`](g) or [`float`](g):
113
114 ```go-html-template
115 {{ $books := where site.RegularPages "Section" "eq" "books" }}
116
117 {{ $pages := where $books "Params.price" "eq" 42 }}
118 {{ $pages := where $books "Params.price" "ne" 42.67 }}
119 {{ $pages := where $books "Params.price" "ge" 42 }}
120 {{ $pages := where $books "Params.price" "gt" 42.67 }}
121 {{ $pages := where $books "Params.price" "le" 42 }}
122 {{ $pages := where $books "Params.price" "lt" 42.67 }}
123 ```
124
125 ### Boolean comparison
126
127 Compare the value of the given field to a [`bool`](g):
128
129 ```go-html-template
130 {{ $books := where site.RegularPages "Section" "eq" "books" }}
131
132 {{ $pages := where $books "Params.fiction" "eq" true }}
133 {{ $pages := where $books "Params.fiction" "eq" false }}
134 {{ $pages := where $books "Params.fiction" "ne" true }}
135 {{ $pages := where $books "Params.fiction" "ne" false }}
136 ```
137
138 ### Member comparison
139
140 Compare a [`scalar`](g) to a [`slice`](g).
141
142 For example, to return a slice of pages where the `color` page parameter is either "red" or "yellow":
143
144 ```go-html-template
145 {{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}
146
147 {{ $colors := slice "red" "yellow" }}
148 {{ $pages := where $fruit "Params.color" "in" $colors }}
149 ```
150
151 To return a slice of pages where the `color` page parameter is neither `red` nor `yellow`:
152
153 ```go-html-template
154 {{ $fruit := where site.RegularPages "Section" "eq" "fruit" }}
155
156 {{ $colors := slice "red" "yellow" }}
157 {{ $pages := where $fruit "Params.color" "not in" $colors }}
158 ```
159
160 ### Intersection comparison
161
162 Compare a `slice` to a `slice`, returning elements with common values. This is frequently used when comparing taxonomy terms.
163
164 For example, to return a slice of pages where any of the terms in the `genres` taxonomy are "suspense" or "romance":
165
166 ```go-html-template
167 {{ $books := where site.RegularPages "Section" "eq" "books" }}
168
169 {{ $genres := slice "suspense" "romance" }}
170 {{ $pages := where $books "Params.genres" "intersect" $genres }}
171 ```
172
173 ### Regular expression comparison
174
175 To return a slice of pages where the `author` page parameter begins with either "victor" or "Victor":
176
177 ```go-html-template
178 {{ $pages := where .Site.RegularPages "Params.author" "like" `(?i)^victor` }}
179 ```
180
181 {{% include "/_common/functions/regular-expressions.md" %}}
182
183 > [!NOTE]
184 > Use the `like` operator to compare string values. Comparing other data types will result in an empty slice.
185
186 ### Date comparison
187
188 Compare predefined front matter dates, or custom front matter dates.
189
190 #### Predefined dates
191
192 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.
193
194 For example, to return a slice of pages that were created before the current year:
195
196 ```go-html-template
197 {{ $startOfYear := time.AsTime (printf "%d-01-01" now.Year) }}
198 {{ $pages := where .Site.RegularPages "Date" "lt" $startOfYear }}
199 ```
200
201 #### Custom dates
202
203 With custom front matter dates, the comparison depends on the front matter data format (TOML, YAML, or JSON).
204
205 > [!NOTE]
206 > Using TOML for pages with custom front matter dates enables precise date comparisons.
207
208 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.
209
210 In the TOML example below, note that the event date is not quoted.
211
212 ```md {file="content/events/2024-user-conference.md"}
213 +++
214 title = '2024 User Conference"
215 eventDate = 2024-04-01
216 +++
217 ```
218
219 To return a slice of future events:
220
221 ```go-html-template
222 {{ $events := where .Site.RegularPages "Type" "events" }}
223 {{ $futureEvents := where $events "Params.eventDate" "gt" now }}
224 ```
225
226 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 over the slice:
227
228 ```go-html-template
229 {{ $events := where .Site.RegularPages "Type" "events" }}
230 {{ $futureEvents := slice }}
231 {{ range $events }}
232 {{ if gt (time.AsTime .Params.eventDate) now }}
233 {{ $futureEvents = $futureEvents | append . }}
234 {{ end }}
235 {{ end }}
236 ```
237
238 ### Nil comparison
239
240 To return a slice of pages where the "color" parameter is present in front matter, compare to `nil`:
241
242 ```go-html-template
243 {{ $pages := where .Site.RegularPages "Params.color" "ne" nil }}
244 ```
245
246 To return a slice of pages where the "color" parameter is not present in front matter, compare to `nil`:
247
248 ```go-html-template
249 {{ $pages := where .Site.RegularPages "Params.color" "eq" nil }}
250 ```
251
252 In both examples above, note that `nil` is not quoted.
253
254 ### Nested comparison
255
256 These are equivalent:
257
258 ```go-html-template
259 {{ $pages := where .Site.RegularPages "Type" "tutorials" }}
260 {{ $pages = where $pages "Params.level" "eq" "beginner" }}
261 ```
262
263 ```go-html-template
264 {{ $pages := where (where .Site.RegularPages "Type" "tutorials") "Params.level" "eq" "beginner" }}
265 ```
266
267 ### Portable section comparison
268
269 Useful for theme authors, avoid hardcoding section names by using the `where` function with the [`MainSections`][] method on a `Site` object.
270
271 ```go-html-template
272 {{ $pages := where .Site.RegularPages "Section" "in" .Site.MainSections }}
273 ```
274
275 With this construct, a theme author can instruct users to specify their main sections in their project configuration:
276
277 {{< code-toggle file=hugo >}}
278 mainSections = ['blog','galleries']
279 {{< /code-toggle >}}
280
281 If `mainSections` is not defined in your project configuration, the `MainSections` method returns a slice with one element---the top-level section with the most pages.
282
283 ### Boolean/undefined comparison
284
285 Consider this project structure:
286
287 ```tree
288 content/
289 ├── posts/
290 │ ├── _index.md
291 │ ├── post-1.md <-- front matter: exclude = false
292 │ ├── post-2.md <-- front matter: exclude = true
293 │ └── post-3.md <-- front matter: exclude not defined
294 └── _index.md
295 ```
296
297 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.
298
299 #### Equality test
300
301 This template:
302
303 ```go-html-template
304 <ul>
305 {{ range where .Site.RegularPages "Params.exclude" "eq" false }}
306 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
307 {{ end }}
308 </ul>
309 ```
310
311 Is rendered to:
312
313 ```html
314 <ul>
315 <li><a href="/posts/post-1/">Post 1</a></li>
316 </ul>
317 ```
318
319 This template:
320
321 ```go-html-template
322 <ul>
323 {{ range where .Site.RegularPages "Params.exclude" "eq" true }}
324 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
325 {{ end }}
326 </ul>
327 ```
328
329 Is rendered to:
330
331 ```html
332 <ul>
333 <li><a href="/posts/post-2/">Post 2</a></li>
334 </ul>
335 ```
336
337 #### Inequality test
338
339 This template:
340
341 ```go-html-template
342 <ul>
343 {{ range where .Site.RegularPages "Params.exclude" "ne" false }}
344 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
345 {{ end }}
346 </ul>
347 ```
348
349 Is rendered to:
350
351 ```html
352 <ul>
353 <li><a href="/posts/post-2/">Post 2</a></li>
354 <li><a href="/posts/post-3/">Post 3</a></li>
355 </ul>
356 ```
357
358 This template:
359
360 ```go-html-template
361 <ul>
362 {{ range where .Site.RegularPages "Params.exclude" "ne" true }}
363 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
364 {{ end }}
365 </ul>
366 ```
367
368 Is rendered to:
369
370 ```html
371 <ul>
372 <li><a href="/posts/post-1/">Post 1</a></li>
373 <li><a href="/posts/post-3/">Post 3</a></li>
374 </ul>
375 ```
376
377 To exclude a page with an undefined field from a boolean _inequality_ test:
378
379 1. Create a slice using a boolean comparison
380 1. Create a slice using a `nil` comparison
381 1. Subtract the second slice from the first slice using the [`collections.Complement`][] function.
382
383 This template:
384
385 ```go-html-template
386 {{ $p1 := where .Site.RegularPages "Params.exclude" "ne" true }}
387 {{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }}
388 <ul>
389 {{ range $p1 | complement $p2 }}
390 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
391 {{ end }}
392 </ul>
393 ```
394
395 Is rendered to:
396
397 ```html
398 <ul>
399 <li><a href="/posts/post-1/">Post 1</a></li>
400 </ul>
401 ```
402
403 This template:
404
405 ```go-html-template
406 {{ $p1 := where .Site.RegularPages "Params.exclude" "ne" false }}
407 {{ $p2 := where .Site.RegularPages "Params.exclude" "eq" nil }}
408 <ul>
409 {{ range $p1 | complement $p2 }}
410 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
411 {{ end }}
412 </ul>
413 ```
414
415 Is rendered to:
416
417 ```html
418 <ul>
419 <li><a href="/posts/post-1/">Post 2</a></li>
420 </ul>
421 ```
422
423 [`MainSections`]: /methods/site/mainsections/
424 [`collections.Complement`]: /functions/collections/complement/
425 [`date`]: /methods/page/date/
426 [`lastmod`]: /methods/page/lastmod/
427 [`time.Time`]: https://pkg.go.dev/time#Time