Build shortcode with array-like parameters

I would like to build a shortcode that outputs mutiple icons with custom labels. Here is how the shortcode would be used in practice:

{{< icons "icon1" "icon1 fancy label" "icon2" "icon2 fancy label" >}}
<!-- The list of icons could be longer ->

I’m having some trouble implementing the template like so:

{{ range $i,$e := .Params }}
   <img src = '/imageDiretory/{{ icon }}.extension' alt = '{{ iconLabel }}'>
   <div class = 'someFancyClass'>{{ iconLabel }}</div>
   icon1 & icon 2 would be the icon values
   the other values would be the icon Labels   
{{ end }}

The problem with the above implementation is that it wouldn’t quite work because every two iterations would cover one icon details. I hope I’m being clear :slight_smile:

Has anyone come across this sort of scenario? Or someone with some neat approach?

Thanks in advance.

Have a look at .Get (see the figure.html shortcode as example).

1 Like

Another option is to pass your label and icon as a single string, separated by a delimiter, such as a colon. Then split them in your shortcode.

For example, say you call the shortcode as:

{{< icons "label 1:icon 1" "label 2:icon 2" "label 3:icon 3" >}}

And the shortcode is defined as:

{{ range .Params }}
  {{ $arg := split . ":" }}
  {{ $label := index $arg 0 }}
  {{ $icon := index $arg 1 }}
  {{ printf "%s = %s" $label $icon }}
{{ end }}

The generated html will be:

  label 1 = icon 1

  label 2 = icon 2

  label 3 = icon 3

I like this, looks elegant enough :slight_smile:. Thank you @zwbetz

1 Like

@kaushalmodi, thanks .Get works well with named or positional parameters. That wouldn’t be helpful in this context.

1 Like