Loading .Site.Data json via string?

I have tried to load json files dynamically, depending on the page I am on.

It works with partials:

    <div>
        <h1>Title</h1>
            {{ $partial := replaceRE "^(.*)[\\/]$" "partials$1.html" .Page.RelPermalink }}
            {{ $file := (printf "layouts/%s" $partial) }}
            {{ if (fileExists $file) }}
                {{ partial $partial . }}
            {{ end }}
    </div>

Is there any way I can load a json file this way and process it within a partial or shortcode?
The issue is, I need to use the RelPermalink as file name and directory.

I am pretty sure I misunderstand what you want (given that there is no JSON in your code sample), but If it’s about loading a json file into a variable, this is the way:

{{ $dataJ := getJSON "content/" .File.Dir "data.json" }}
{{ with $dataJ.somesubkey }}
<p>{{ . | safeHTML }}</p>
{{ end }}

edit: The .File.Dir extends to the directory of the current file. I use that in page-bundles where json lives right next to the index.md file.

1 Like
data
└── foo.json
{{- $myDataFile := "foo" -}}
{{- range $k, $v := index .Site.Data $myDataFile }}
  {{ $k }} = {{ $v }}
{{- end -}}
1 Like

Thanks to both of you. The solution from @davidsneighbour was the on I needed.

In single.html:

        {{ $file := replaceRE "^(.*)[\\/]$" "data$1.json" .Page.RelPermalink }}
        {{ .Scratch.Set "location" $file }}
        {{ partial "partials/template" . }}

In the partial:

 {{ $location := .Scratch.Get "location" }}
 {{ if (fileExists $location ) }}
     {{ $dataJ := getJSON  $location }}
         {{ range $dataJ.topkey }}
              {{ .element }}
         {{ end }}
{{ end }}

This works really nice. Thanks again.

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