An equivalent to "for i := k" loop?


Is there a way of constructing a loop that would iterate over numbers instead of collections? An equivalent to:

for i := 1; i <= .Params.images; i++ {}

I have files inside /content/a/b/ which are named image_1.jpg, image_2.jpg, … image_9.jpg and I provide images: 9 parameter in the front matter of /content/a/b/ file to manually specify how many of those files are in the leaf bundle.

I’d like to use this parameter (which might be different for each leaf bundle from section a) in /themes/mytheme/layouts/index.html to iterate through all of these images for each page found in /content/a/, that I’m listing on the Home page.

The range is the only loop construct, but you can do:

{{ $i, $e := range .Params.images }}
{{ $imageName := (printf "image_%d.jpg" (add $i 1) }}
{{ end }}
1 Like

Hi @bep. For some reason Hugo doesn’t like this line and throws:

parse failed: template: index.html:22: too many declarations in command

OK; I always get that syntax wrong when taking from memory, try:

1 Like

Unfortunately Hugo now says that:

executing "main" at <.Params.images>: range can't iterate over 9

Okay, this error message gave me a clue and I found this post. Combined with your code it works like a charm. Thanks @bep!

{{ range $i := (seq .Params.images) }}
	{{ $imageName := (printf "image_%d.jpg" (add $i 0)) }}
{{ end }}

Ah, ok … so .Params.images is a number …

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.