range
文法
range COLLECTION
偽値 (falsy value) とは false、0、nil ポインター、インターフェース値、配列、スライス、マップ、長さゼロの文字列、ゼロの time.Time 値、です。
これ以外はすべて真値 (truthy) です。
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
{{ . }} → foo bar baz
{{ end }}
Use with the else statement:
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
<p>{{ . }}</p>
{{ else }}
<p>The collection is empty</p>
{{ end }}
Within a range block:
- Use the
continuestatement to stop the innermost iteration and continue to the next iteration - Use the
breakstatement to stop the innermost iteration and bypass all remaining iterations
Understanding context
At the top of a page template, the context (the dot) is a Page object. Within the range block, the context is bound to each successive element.
With this contrived example that uses the seq function to generate a slice of integers:
{{ range seq 3 }}
{{ .Title }}
{{ end }}
Hugo will throw an error:
can't evaluate field Title in type int
The error occurs because we are trying to use the .Title method on an integer instead of a Page object. Within the range block, if we want to render the page title, we need to get the context passed into the template.
This template will render the page title three times:
{{ range seq 3 }}
{{ $.Title }}
{{ end }}
Array or slice of scalars
This template code:
{{ $s := slice "foo" "bar" "baz" }}
{{ range $s }}
<p>{{ . }}</p>
{{ end }}
Is rendered to:
<p>foo</p>
<p>bar</p>
<p>baz</p>
This template code:
{{ $s := slice "foo" "bar" "baz" }}
{{ range $v := $s }}
<p>{{ $v }}</p>
{{ end }}
Is rendered to:
<p>foo</p>
<p>bar</p>
<p>baz</p>
This template code:
{{ $s := slice "foo" "bar" "baz" }}
{{ range $k, $v := $s }}
<p>{{ $k }}: {{ $v }}</p>
{{ end }}
Is rendered to:
<p>0: foo</p>
<p>1: bar</p>
<p>2: baz</p>
Array or slice of maps
This template code:
{{ $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 }}
Is rendered to:
<p>John is 30</p>
<p>Will is 28</p>
<p>Joey is 24</p>
Array or slice of pages
This template code:
{{ range where site.RegularPages "Type" "articles" }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
Is rendered to:
<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>
Maps
This template code:
{{ $m := dict "name" "John" "age" 30 }}
{{ range $k, $v := $m }}
<p>key = {{ $k }} value = {{ $v }}</p>
{{ end }}
Is rendered to:
<p>key = age value = 30</p>
<p>key = name value = John</p>
Unlike ranging over an array or slice, Hugo sorts by key when ranging over a map.
詳しくは Go の text/template ドキュメントを参照してください。