Simple dynamic site params

How can I dynamically pick a config entry under the .Site.Params container in a simple way?

What I want is a mapping between the current page type and a color which should be displayed for that page type. For that, I created the mapping on my config.toml file:

# config.toml 
[params.pageColors]
  about = "red"
  blog  = "blue"

 # about.html
 {{ $pageColor := .Site.Params.PageColors.About }} # Correctly outputs "red"
 <h1 class="{{ $pageColor }}">About</h1>

The above approach is static, so I want .About to be replaced by a variable which holds the page type name.

The following code block does not work and/or have wrong syntax - but its what I expected to be a simple way to accomplish what I want.

# blog.html
{{ $pageType := "blog" }} # Setting pageType to a static string for example
{{ $pageColor := .Site.Params.PageColors.$pageType }} # Does not work
{{ $pageColor := .Site.Params.PageColors[$pageType] }} # Does not work also
<h1 class="{{ $pageColor }}">Blog</h1>

What works is the following example:

{{ $pageType := "blog" }}
{{ $context := . }}
{{ range $key, $value := .Site.Params.PageColors }}
    {{ if eq $pageType $key }}
        {{ $context.Scratch.Set "pageColor" $value }}
    {{ end }}
{{ end }}
<h1 class="{{ .Scratch.Get "pageColor"}}">Blog</h1>

Is there a simpler way to accomplish what I want?

Hi,

You will want to use index: https://gohugo.io/functions/index-function/

Something like

{{ $pageColor := index .Site.Params.pageColors $pageType }}
1 Like

Yey :partying_face: that was what I was looking for, thanks.