[SOLVED] Using a variable when accessing data location

I’m attempting to use a variable when accessing a data file. I have a data file that will be used for each piece of content. To keep them aligned, I’m expecting the filename of the content to have a matching filename for the datafile.

My code looks like this:

{{ range ($.Site.Data.project .File.BaseFileName .milestones) }} <tr> {{ range . }} <td>{{ . }}</td> {{ end }} </tr> {{ end }}

I’m expecting it to iterate over .Site.Data.project.contentname.milestones, but it is throwing an error saying that project is not a method by has arguments.

You will have to use the index func, ala:

{{ range ((index $.Site.Data.project .File.BaseFileName).milestones) }}
1 Like

I attempted this once before and get a panic error. Here is the attempted code:

{{ range ((index $.Site.Data.project .File.BaseFileName).milestones) }}
   <tr>
     {{ range . }}
       <td>{{ . }}</td>
     {{ end }}
   </tr>
 {{ end }}

And the result in the terminal:

panic: reflect: Zero(nil) [recovered] panic: reflect: Zero(nil)

Sure, but you will have to break it up an wrap it in a with or something, because I’ll assume not every page has milestones attached to it, hence the panics.

Something ala:

$p := (index $.Site.Data.project .File.BaseFileName)
{{ with $p }}
{{ range .milestones }}
   <tr>
     {{ range . }}
       <td>{{ . }}</td>
     {{ end }}
   </tr>
 {{ end }}
 {{ end }}
2 Likes

Good call!

I had 2 pages created and only a data file for one. The panic was because the other data file didn’t exist. Thanks!