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