The Go Templates make heavy use of range
to iterate over a Map, Array, or Slice.
Version
Hugo 0.92
Using Context
Using range
to iterate over an Array to render <li>
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="alpine.js" defer></script>
<link rel="stylesheet" href="output.css" />
{{ $numbers := slice 1 2 3 }}
</head>
<body>
<ul class="ml-6 list-disc">
{{ range $numbers }}
<li>{{ . }}</li>
{{ end }}
</ul>
</body>
</html>
Line 8
{{ $numbers := slice 1 2 3 }}
slice
: define an Array with[1, 2, 3]
Line 11
<ul class="ml-6 list-disc">
{{ range $numbers }}
<li>{{ . }}</li>
{{ end }}
</ul>
range
: pass Array directly torange
. The.
represents an element in Array
Declaring Variable
Same result but using a variable with range
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="alpine.js" defer></script>
<link rel="stylesheet" href="output.css" />
{{ $numbers := slice 1 2 3 }}
</head>
<body>
<ul class="ml-6 list-disc">
{{ range $x := $numbers }}
<li>{{ $x }}</li>
{{ end }}
</ul>
</body>
</html>
Line 12
{{ range $x := $numbers }}
<li>{{ $x }}</li>
{{ end }}
range
: declare a variable for Array element
Declaring Index
Using range
to iterate over Array with index.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="alpine.js" defer></script>
<link rel="stylesheet" href="output.css" />
{{ $numbers := slice 1 2 3 }}
</head>
<body>
<ul class="ml-6 list-disc">
{{ range $i, $x := $numbers }}
<li>{{ $i }}: {{ $x }}</li>
{{ end }}
</ul>
</body>
</html>
Line 12
{{ range $i, $x := $numbers }}
<li>{{ $i }}: {{ $x }}</li>
{{ end }}
range
: first declared variable will map to each element’s index
Empty Array
We can also define how to deal with an empty Array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="alpine.js" defer></script>
<link rel="stylesheet" href="output.css" />
{{ $numbers := slice }}
</head>
<body>
<ul class="ml-6 list-disc">
{{ range $numbers }}
<li>{{ . }}</li>
{{ else }}
<li>N/A</li>
{{ end }}
</ul>
</body>
</html>
Line 12
{{ range $numbers }}
<li>{{ . }}</li>
{{ else }}
<li>N/A</li>
{{ end }}
else
: If the Array passed into therange
is zero-length then theelse
statement is evaluated
Conclusion
range
also support index and empty Array withelse