2

I have maintained an authors.json file inside of the data folder in my Hugo setup which contains an object of author details which looks something like this

{
    "john_doe":{
        "name":"john_doe",
        "github":"john_doe",
        "description":"Some Sample Description"
    }
}

Now, on the template side I want to access the details in the john_doe property. I tried doing something like

{{.Site.Data.authors[name]}}

But this doesn't seem to work. Please can anyone help?

  • `{{ .Site.Data.authors.john_doe }}` [link](https://gohugo.io/templates/data-templates/#example-accessing-named-values-in-a-data-file) – mkopriva Oct 27 '21 at 07:52
  • @mkopriva my bad, I need to access john_doe dynamically, maybe with name variable – shivaraj bakale Oct 27 '21 at 08:03
  • 1
    Then use the `index` template function, like so: `{{ index .Site.Data.authors $name "github" }}` – mkopriva Oct 27 '21 at 08:06
  • https://pkg.go.dev/text/template@go1.17.2#hdr-Functions `index`: Returns the result of indexing its first argument by the following arguments. Thus `"index x 1 2 3"` is, in Go syntax, `x[1][2][3]`. Each indexed item must be a **map**, slice, or array. – mkopriva Oct 27 '21 at 08:08
  • Just FYI, in case you are unaware, variables in Go templates must start with `$`. So `name` is *not* a valid template variable, but `$name` is. – mkopriva Oct 27 '21 at 08:16
  • @mkopriva Got it. Thanks a lot! That was really helpful – shivaraj bakale Oct 27 '21 at 09:00
  • @mkopriva - Mate, not understanding here. If you need to access the name property then, just access the name property. It's not dynamic, the value assigned to it is. What exactly are you running into? – Rogelio Oct 28 '21 at 21:10
  • 1
    I got it @mkopriva. Thanks for the help :) – shivaraj bakale Oct 30 '21 at 06:53

0 Answers0