Dynamically append json files to render on a page

In params I have something like this (adjusted for brevity)…

[[childdatal]]
name = "sitedata1"
file = "site.Data.file1.items"

[[childata]]
name = "sitedata2"
file = "site.Data.file2.items"

Now I want to dynamically append these into a combined object to iterate and render Which I have in my list.html page, something like this…

{{ $merged := slice }}
{{ range  $childdata }}
  {{ $file := .file  }}
  {{ $merged = $merged | append $file }}
  # //Render combined json data here
  #{{ $file }}
{{ end }}

In the resulting function if I uncomment {{ $file }} I see the correct list of file references.
If I hard code {{ $merged = $merged | append site.Data.file1.items }} I get the correct unpacking of the underlying json, but otherwise it treats $file as a variable representing a string.

What needs to happen to treat $file as a reference to the json (as when its hard-coded) instead of string?

Many Thanks

Mark

Keep in mind, that site.Data is a method, but "site.Data" is a string

To access variable fields with site.Data you have to use the index function:

# if there's a data/myfile.json in your site
$file := "myfile"
index site.Data $file

data files

data/file1.json and data/file2.json with content

{
   "items": {
      "f1i": "items of file one"
   }
}

site config:

I moved childData to the params key because of deprecation of use defined params in the toplevel.

[params]
   [[params.childdata]]
      name = "sitedata1"
      file = "file1"

   [[params.childdata]]
      name = "sitedata2"
      file = "file2"

Template

I hardcoded the items subkey. If this is dynamic in your case you need another call to index as you cannot do something like index "a.b"

 {{ $merged := slice }}
 {{ range site.Params.Childdata }}
    {{ $fileData := index site.Data .file }}
    {{ $merged = $merged | append $fileData.items }}
 {{ end }}
1 Like