blob: cf01633b4d5cc2a4c87be7bda4870550972bec2c (
plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
|
---
title: range
description: Iterates over slices, maps, and page collections.
categories: [functions]
keywords: []
menu:
docs:
parent: functions
function:
aliases: []
returnType:
signatures: [range COLLECTION]
relatedFunctions:
- with
- range
aliases: [/functions/range]
toc: true
---
{{% readfile file="/functions/_common/go-template-functions.md" %}}
## Slices
Template:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
<p>{{ . }}</p>
{{ end }}
```
Result:
```html
<p>foo</p>
<p>bar</p>
<p>baz</p>
```
Template:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $v := $s }}
<p>{{ $v }}</p>
{{ end }}
```
Result:
```html
<p>foo</p>
<p>bar</p>
<p>baz</p>
```
Template:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $k, $v := $s }}
<p>{{ $k }}: {{ $v }}</p>
{{ end }}
```
Result:
```html
<p>0: foo</p>
<p>1: bar</p>
<p>2: baz</p>
```
## Maps
Template:
```go-html-template
{{ $m := slice
(dict "name" "John" "age" 30)
(dict "name" "Will" "age" 28)
(dict "name" "Joey" "age" 24)
}}
{{ range $m }}
<p>{{ .name }} is {{ .age }}</p>
{{ end }}
```
Result:
```html
<p>John is 30</p>
<p>Will is 28</p>
<p>Joey is 24</p>
```
## Page collections
Template:
```go-html-template
{{ range where site.RegularPages "Type" "articles" }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
```
Result:
```html
<h2><a href="/articles/article-3/">Article 3</a></h2>
<h2><a href="/articles/article-2/">Article 2</a></h2>
<h2><a href="/articles/article-1/">Article 1</a></h2>
```
## Break
Use the `break` statement to stop the innermost iteration and bypass all remaining iterations.
Template:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
{{ if eq . "bar" }}
{{ break }}
{{ end }}
<p>{{ . }}</p>
{{ end }}
```
Result:
```html
<p>foo</p>
```
## Continue
Use the `continue` statement to stop the innermost iteration and continue to the next iteration.
Template:
```go-html-template
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
{{ if eq . "bar" }}
{{ continue }}
{{ end }}
<p>{{ . }}</p>
{{ end }}
```
Result:
```html
<p>foo</p>
<p>baz</p>
```
|