File: IndexFunction.md

package info (click to toggle)
hugo 0.131.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 45,580 kB
  • sloc: javascript: 31,172; xml: 248; makefile: 73; sh: 42
file content (51 lines) | stat: -rw-r--r-- 1,184 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
---
title: collections.Index
description: Returns the object, element, or value associated with the given key or keys.
categories: []
keywords: []
action:
  aliases: [index]
  related: []
  returnType: any
  signatures:
    - collections.Index COLLECTION KEY...
aliases: [/functions/index,/functions/index-function]
---

Each indexed item must be a map or a slice:

```go-html-template
{{ $s := slice "a" "b" "c" }}
{{ index $s 0 }} → a
{{ index $s 1 }} → b

{{ $m := dict "a" 100 "b" 200 }}
{{ index $m "b" }} → 200
```

Use two or more keys to access a nested value:

```go-html-template
{{ $m := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
{{ index $m "c" 1 }} → 20

{{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ index $m "c" "e" }} → 20
```

You may also use a slice of keys to access a nested value:

```go-html-template
{{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
{{ $s := slice "c" "e" }}
{{ index $m $s }} → 20
```

Use the `collections.Index` function to access a nested value when the key is variable. For example, these are equivalent:

```go-html-template
{{ .Site.Params.foo }}

{{ $k := "foo" }}
{{ index .Site.Params $k }}
```