Introduction
In Hugo, to loop through list of items we use Range function which comes from go language. range
, iterates over a map, slice or array.
{{ range .Site.RegularPages }}
{{ .Title }}
{{ end }}
Also, notice inside range
the scope is different. .Title
refers to the page in current iteration. If we need the top level variable we should the dollar sign $.Title
. Scope is another topic and here is a very useful blog-post already written.
C Style For Loop
Loops in Hugo is a little different. We need small tricks to get a classic C style for loop. range
is more like a “foreach” function than a “for”. Yet, this doesn’t mean we can’t use iteration number.
for (int i = 0, i < upperBound, i ++)
{
//do something;
}
Key Value Pairs
So, how can we get the iteration number (or index)? Let’s start with a simple example using context (the dot) and seq function.
{{ range $num := (seq 5) }}
{{ . }}
{{ end }}
# 1 2 3 4 5
We can use key-value pairs to generate the iteration number. In the example below $index
is our key.
{{ range $index, $num := (seq 5) }}
{{ $index }}
{{ end }}
# 0 1 2 3 4
$index
is not a keyword here, just a variable we named, we could’ve call it $foo
. Also, notice that it’s zero based.
We need to define the value too. See the difference in following examples:
{{ range $index, $.Site.RegularPages }}
{{ $index }} <br>
{{ end }}
# Page(/hugo/convert-dates-into-your-language.md)
# Page(/hugo/last-modified-date-in-hugo.md)
# Page(/hugo/tag-cloud-in-hugo.md)
# Page(/jekyll/rss-feed-in-jekyll.md)
# ...
# Page(/hugo/loops-in-hugo.md)
# Page(/hugo/math-typesetting-in-hugo.md)
{{ range $index, $val := $.Site.RegularPages }}
{{ $index }}
{{ end }}
# 0 1 2 3 ... 49 50
Scracth Function
Alternatively, we can use the Scracth function. Most of the time, key, value pairs above will suffice. Yet, $index
always starts from 0 and increments by 1 at each iteration. With, scracth we don’t have to start from 0 and increment by 1. It’s up to us.
{{ $.Scratch.Set "index" 0 }}
{{ range $pages }}
{{ $.Scratch.Set "index" (add ($.Scratch.Get "index") 1) }}
//do something
{{ end }}
Main purpose of scratch is handling scoping issues. It basically allows us to set variables into the context of the page. Then we can manipulate, change or get these scracth variables from other pages, it’s most helpful when creating shortcodes and partials. Here is a good article about scracth.
Nested Loops in Hugo
Nested loops in Hugo is easy but you should know that range has it’s own scope and you need to use the dollar sign $
to get variable from the root page. Here is an example I’ve used before.
{{ $sections := where $.Site.Pages ".Kind" "section" }}
{{ range $sections }}
<h3><a href="{{ .Permalink }}">{{ .Title }}</a></h3>
{{ $sectionName := .Section | singularize }}
{{ $pages := where $.Site.RegularPages ".Section" $sectionName }}
{{ range $pages.ByParam "date" }}
{{.Params.date}} · {{.Title}}
{{ end }}
{{ end }}