How do you pass variables into index function?

I have a large data-driven website, and I rely on json data templates. But I dont know how to tell it which json file to use the index function on.

I thought I would use {{ .Title }} and write something like this:

{{ index .Site.Data.$var.tree 0 }}

or

{{ index .Site.Data.(.Title).tree 0 }}

or

{{ index .Site.Data.(printf “%s” $var).tree 0 }}

I dont know how to do this at all, and there doesnt seem to be any documentation for it. I cant even find any documentation of this:

{{ $variable := .Title }}

The above syntax is nowhere to be found in the variables documentation so what is it?

Is my approach even the way Hugo is meant to handle lots of data points?

I’m still super new so I don’t know how correct this is, but the way I’m doing this now is something like:

{{ index (index .Site.Data .Title) "tree" }}
1 Like

Oh… No matter what I get a compile error because the title isnt defined in compilation, but it lets it compile anyway.

So your code works fine, and it can be written without two index function calls instead:

{{ index .Site.Data .Title “tree” }}

But it does need quotations around the properties, I would never have known that.
And if its multiple (nested) object properties after, you do this:

{{ index .Site.Data .Title “tree” “branch” }}

If its an array:

{{ index .Site.Data .Title “array” 0 }}

Now I can do what I need, but im left wondering if there is any good practice for data driven sites with lots of different data points other than calling {{ index }} 60 times per page for 10,000 pages.

1 Like