Shortcode with custom key value to range

Hi everyone,
i’m new to Hugo and i’m testing it on a personal project i’m working on.

What i’d like to achieve is to use a shortcode to range through the results of my dataset in my page templates and i want it to be flexible by passing the name of the key value as argument so i can retrieve the data i need.

The problem i’m facing though is that the custom value is passed as string and throws me an error.
I’ve tried to use the slice and index functions for trying to map the collection the way i want but i can’t make this work.

Is it possible to do the thing i’m trying to achieve or should i hard code the range function in every page?

Thanks in advance to everyone who will take some time for helping me!

Some example code:
layouts/shordcodes/steps.html

{{$collection := .Site.Data.steps}}
{{$customKeyValue := .Get 0}}  // Might be item-a or item-b according to the example

{{range $collection}}

  {{range  $customKeyValue}}
  {{.title}}
  {{.description}}
  {{end}}

{{end}}

data/steps.json

{
  "steps": {
    "item-a": 
    [
      {
      "title":"step1",
      "description": "Some text"
      },
      {
        "title":"step2",
        "description": "Some text"
      },
    ],

    "item-b": [
      {
        "title":"step 1",
        "description": "Some text"
        },
        {
          "title": "step 2",
          "description": "Some text"
        },
    ],
}
}

You need to use the index function within the shortcode to get the data, then you can work with it.

I have already tried the index function as the example below. It doesn’t throws errors but even data.
If i debug the $customKeyValue with printf it returns nil.

Is it a syntax error somewhere?

{{$collection := .Site.Data.steps}}
{{$key:= .Get 0}} 
{{$customKeyValue:= index $collection $key}}

{{range $collection}}

  {{range  $customKeyValue}}
  {{.title}}
  {{.description}}
  {{end}}

{{end}}

EDIT

I forgot to put the shortcode call
I’m passing the value like that

{{< steps `item-a` >}}

Your data structure has an “outer” steps key (the file name) and an “inner” steps key (inside the data file).

{{< steps "item-a" >}}
{{ range index site.Data.steps "steps" (.Get 0) }}
  {{.title}}
  {{.description}}
{{ end }}

or

{{ range index site.Data.steps.steps (.Get 0) }}
  {{.title}}
  {{.description}}
{{ end }}

Ah! These names tricked me so hard and got me on the wrong way. :sweat_smile:

Thank you for the correction @jmooring

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.