Using variable in range for data templates

Hello!
I’m trying to compose a range statement with a variable in it to be “dynamic” if the source JSON it has its information from gets updated.

The JSON files are named like this “firstlastname.json” and I have no trouble accessing / working with them from
{{ range $.Site.Data.players.firstlastname.information }}

I read this and my code now looks like this:

{{ $myjsonfile := .firstlastname }}
{{ range (index $.Site.Data.players $myjsonfile).information }}
    {{ .fullname }}
{{ end }}

Output for $myjsonfile is: .firstlastname (the correct JSON file name for one of the players).

I have no error or other output from this range I could work with. Any hints?

Cheers! :slight_smile:

Please provide example of data file.

You mean of the JSON? Sure, looks like this:

{
  "information": [
    {
      "fullname": "Full Name",
      "numberofgames": 6,
      "pointstotal": 8,
      "winstotal": 2,
      "drawstotal": 2,
      "lossestotal": 2,
      "pointsaverage": 1.3333333333333333,
      "winpercentage": 33,
      "winchance": "low"
    }
  ],
  "games": [
    {
      "date": "2018-03-18T00:00:00+00:00",
      "fixtureID": -,
      "timestamp": -,
      "leagueid": 78,
      "hometeam": "-",
      "hometeamgoal": 2,
      "awayteam": "-",
      "awayteamgoal": 0,
      "resultforplayer": "win"
    },
    {
      "date": "2018-02-25T00:00:00+00:00",
      "fixtureID": -,
      "timestamp": -,
      "leagueid": 78,
      "hometeam": "-",
      "hometeamgoal": 1,
      "awayteam": "-",
      "awayteamgoal": 2,
      "resultforplayer": "win"
    },
]
}

But as I said, it works fine if I manually enter the filename in the range (range $.Site.Data.players.firstlastname.information), so I THINK this might not be the problem, but I put the range with variable together wrongly.

Interestingly I have no error while implementing the range (index $.Site.Data.players $myjsonfile).information, but nothing in between the range and the end is actually loaded on the page, even if its plain text.

Why is “information” an array instead of an object?

This works as expected:

{{ $myjsonfile := "firstlastname" }}
{{ range (index $.Site.Data.players $myjsonfile).information }}
  {{ .fullname }}
{{ end }}

Try it:

git clone --single-branch -b hugo-forum-topic-40374 https://github.com/jmooring/hugo-testing hugo-forum-topic-40374
cd hugo-forum-topic-40374
hugo server

Thanks, that was it! Since the other topic also had the example for declaring the variable starting with a dot and it matched the general construction of the range, I was convinced I also had to declare it like that. Removed the dot and it worked as expected. Many thanks for your time! :slight_smile:

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