Using a Variable in a Range

#1

Hello,

I have a layout that I’d like to use to pull data from a couple different .JSON files and have created a custom field in the frontmatter in the pages using that layout to reference it. However I seem to be having an issue using it and hoping someone can provide some assistance or suggest another way to accomplish this.

{{ rangePath1 := ".Site.Data.changelog."}}
{{ $type := .Params.changelogtype }}
{{ $rangePath2 := “.releases”}}
{{ $range := print $rangePath1 $type $rangePath2 }}

{{ range $range }}
Range code
{{ end }}

Running the above throws the following error.

range can't iterate over $.Site.Data.changelog.desktop.releases

Hardcoding the above works but I’m hoping to only have to do that as a last resort.

0 Likes

#2

What does your front matter look like?

Edited to add: The reason it fails is because you are iterating over $range, which is a string, and not the data file that you want to iterate over.

You probably want to use index: https://gohugo.io/functions/index-function/#example-load-data-from-a-path-based-on-front-matter-params

0 Likes

#3

Hello,

+++
title = “Desktop Changelog”
publishDate = 2019-04-11
lastMod = 2019-04-12
layout = “changelog”
markup = “mmark”
changelogtype = “desktop”
+++

Thanks for the link, I’ll look into it and give it a try.

0 Likes

#4

Here’s the new error I’m getting.

{{ range (index .Site.Data.changelog .Params.changelogtype).releases }}

<index .Site.Data.cha...>: error calling index: value is nil; should be of type string

{{ .Params.changelogtype }} does show the value correctly.

0 Likes

#5

I was able to find a solution.

{{$type := string .Params.changelogType}}

{{ range (index .Site.Data $type).releases }}
range code
{{ end }}

0 Likes