What's the correct way to reference nested frontmatter keys in a template?

Suppose you have the following YAML frontmatter on a post:

date: 2016-01-01T12:34:56Z
title: "Hello, World"
  name: John
  current_mood: adventurous

We can see that the frontmatter is picking this up by printing it out in the template:

{{ $key := "author" }}
{{ .Param $key }}
// prints: map[name:John current_mood:adventurous]

What if you want one of the subkeys – how would you print the value of, say, author.current_mood in the template? What should we assign to $key in that case?

I think it would be just {{ .Params.author.current_mood }}

Right, but that only works if you know the name of the key in advance. If it’s in a variable, how do you use .Param? I’ll update the post so this is clearer.

1 Like

You can use the index template function. Have a look at the code example of default.

1 Like

@jxf I think @budpart answered you correctly. Just assign {{ $key := .Params.author.current_mood }}. Or are you asking how to range through all values?

Hmm, I think you may have misunderstood me: the variable in question is the author.current_mood part. In this example, you don’t know what key you’re looking up, and the key to look up is stored in that variable.

In other words, how can you find the appropriate value given only a single string?

Oh wow, this is really close, @digitalcraftsman! The sticking point is that $key could contain multiple levels to look up, as in my author.current_mood example, but index wants one argument for each level of nesting.

I think this would work if I split programmatically split $key up first into the individual segments, e.g. by splitting it along periods into a slice. Is there a way to “unpack” or “splat” slices and pass their individual members as arguments to another function? That would solve it.

You could loop through a slice/map etc. with the range keyword. Inside the loop you will can process each item one by one.

I wound up scratching my own itch and submitting a PR:

This feature is now available in Hugo master.