HUGO

{{ range .Site.Data.<variable name> }} --Is This Possible?

I thought it was about time I got to grips with Hugo’s data folder workings, seeing as it’s been there forever and I’ve never used it up to now. The basics seem pretty straightforward but I’ve run into my usual problems when trying to get my head round Hugo/Golang template syntax.

I’ll explain what I’m trying to do by adapting the provided example in the docs and then you clever folks can tell me if this is even possible:

The example I’ve seen has data about the various US states saved in /data/states.json and then loads this into a page with something like this in the template:

 {{range .Site.Data.states}}
<p>{{.name}}</p>
<p>{{.capital}}</p>
 {{end}}

I’m trying to create a scenario where the data loaded depends on the content of different pages, which share a common template.

So, to adapt the above example, say I was doing similar for pages about the counties of the various nations in the British Isles. I have separate pages for England, Scotland, Wales, Ireland and separate data files for each country, with info about its counties. So in my template, I want to embed the appropriate data file for each country.

I can save the name of the associated data file in a frontmatter variable. But is it possible to build the .Site.Data... path using this variable? eg:

Page frontmattter

+++
countryName = "England"
+++

or…

+++
countryName = "Scotland"
+++

or…

+++
countryName = "Wales"
+++

etc.

And then in my template, something akin to:

 {{range .Site.Data.<countryName>}}
<p>{{.countyName}}</p>
<p>{{.countyTown}}</p>
 {{end}}

But I’ve no idea how the syntax would work. Or if it’s even doable? If it is, please enlighten me.

{{ with .Params.countryname }}
  {{ range $k, $v := index site.Data . }}
    {{ printf "%s = %v" $k $v }}<br>
  {{ end }}
{{ end }}
2 Likes

Brilliant. Thanks!

[Sorry for delay in replying. Only just got round to trying it out]

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