Accessing data source from shortcode

I’m attempting to use a shortcode to capture a term and use that term as a reference to a JSON file I have stored in /data, and then ranging over it to print out its contents.

I’m getting an error:

error processing shortcode "shortcodes/tokens.html" for page "foundations/tokens.md": template: shortcodes/tokens.html:5:13: executing "shortcodes/tokens.html" at <$data>: range can't iterate over .Site.Data.design_tokens.accordion

shortcode template (fed “accordion”)

{{ $token := .Get "token" }}
{{ $data := ( printf ".Site.Data.design_tokens.%s" $token) }}

<ul>
    {{ range $data }}
    <li>{{ .NAME }}: {{ .VALUE }}</li>
    {{ end }}
</ul>

data folder contents:

data/design_tokens/accordion.json

accordion.json

{
  "ACCORDION_CONTENT_PADDING": "16px",
  "ACCORDION_HEADER_PADDING": "0 16px",
  "ACCORDION_HEADER_HEIGHT_MIN": "40px",
  "ACCORDION_HEADER_BACKGROUND_COLOR": "#e1e1e1",
  "ACCORDION_SECTION_BORDER_SIZE": "1px",
  "ACCORDION_SECTION_BORDER_STYLE": "solid",
  "ACCORDION_SECTION_BORDER_COLOR": "#e1e1e1"
}

Does this look broken somehow? $data gets built correctly, but is range not seeing that as a proper data location?

The above creates a string, which is not what you want.

Try:

{{ $data :=  index .Site.Data.design_tokens $token }}
1 Like

Thank you, @bep. Here’s my fixed version:

{{ $token := .Get "token" }}
{{ $data :=  index .Site.Data.design_tokens $token }}
<dl>
{{range $index, $element := $data}}
    <dt>{{ $index }}:</dt>
    <dd>{{ $element }}<dd>
{{ end }}
</dl>
2 Likes