Search code examples
variableshugotemplating

Using Variables inside Hugo Data


I have been trying to learn Hugo and have a basic site running. As well as the basic post data structure, I also have images loaded in each post by calling .File.BaseFileName to get the slug of the page and having relevant images named in the static folder.

Alongside the information in each post, I would like to augment each post with information from the data folder and have tried a similar technique of naming a data file the same as the slug (as I did with images in the description above).

However, when coming to reference this, using {{.Site.Data.User0123.Name}} from the example page I need to pass a variable name to replace User0123

I have tried using:

  1. The javascript style bracket syntax - {{.Site.Data.["Variable"].Name}}
  2. declaring a variable of the slug and then using {{.Site.Data.$slug.Name}}

But neither of these worked.

I know I could put all additional info insdiode the post itself but this doesnt work for the flow I'm using, where the posts are generated automatically and I want to augment with additional data.


Solution

  • A colleague actually helped me this - seems the way to solve it, is to use the index function.

    {{ $userData2 := index .Site.Data $slug }}
      <div>boop2 {{$userData2.Name}}: <p>{{ index $userData2 "Short Description" | markdownify }}</p></div>