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.
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.
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.
We can use key-value pairs to generate the iteration number. In the example below
$index is our key.
$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:
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.
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.