Debian Codegraph @

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

raw
1 ---
2 title: collections.Index
3 description: Returns an element or value from the given slice or map at the specified key(s).
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: [index]
9 returnType: any
10 signatures: [collections.Index SLICE|MAP KEY...]
11 aliases: [/functions/index,/functions/index-function]
12 ---
13
14 Each indexed item must be a map or a slice:
15
16 ```go-html-template
17 {{ $s := slice "a" "b" "c" }}
18 {{ index $s 0 }} → a
19 {{ index $s 1 }} → b
20
21 {{ $m := dict "a" 100 "b" 200 }}
22 {{ index $m "b" }} → 200
23 ```
24
25 Use two or more keys to access a nested value:
26
27 ```go-html-template
28 {{ $m := dict "a" 100 "b" 200 "c" (slice 10 20 30) }}
29 {{ index $m "c" 1 }} → 20
30
31 {{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
32 {{ index $m "c" "e" }} → 20
33 ```
34
35 You may also use a slice of keys to access a nested value:
36
37 ```go-html-template
38 {{ $m := dict "a" 100 "b" 200 "c" (dict "d" 10 "e" 20) }}
39 {{ $s := slice "c" "e" }}
40 {{ index $m $s }} → 20
41 ```
42
43 Use the `collections.Index` function to access a nested value when the key is variable. For example, these are equivalent:
44
45 ```go-html-template
46 {{ .Site.Params.foo }}
47
48 {{ $k := "foo" }}
49 {{ index .Site.Params $k }}
50 ```