I have a shortcode with a lot of named parameters. One of those parameters is a list of filenames (it’s for an image gallery shortcode). For example:
{{< gallery width="500px" cols="3" images="apple.jpg, banana.jpg, pineapple.jpg, rutabaga.jpg" >}}
Is there a best practice or existing function to accommodate parameters that have multiple values? I can imagine using the split
function to create a slice
that I could then range
over, but I didn’t know if there was something existing that already handled parameters with multiple values.
You can also do:
{{< gallery width="500px" cols="3" >}}
apple.jpg
banana.jpg
pineapple.jpg
rutabaga.jpg
{{< /gallery >}}
layouts/shortcodes/gallery.html
{{/* Replace CRLF with LF. */}}
{{ $items := strings.Replace .Inner "\r\n" "\n" }}
{{/* Remove leading and trailing newlines. */}}
{{ $items = strings.Trim $items "\n" }}
{{/* Create slice. */}}
{{ $items = strings.Split $items "\n" }}
{{/* Do something. */}}
{{ range $items }}
...
{{ end }}
@jmooring Thanks! In the end that’s what I ended up doing. I realized that .Inner
could be manipulated and then knew it was a much more sustainable route. Ultimately I’m using YAML-like syntax to allow for additional fields:
{{< gallery >}}
- apple.jpg
A red apple
My favorite type of apple!
- banana.jpg
An unripe banana
- pineapple.jpg
Fresh pineapple
I love pineapple the most
{{</ gallery >}}
{{- $items := split .Inner "\n- " -}}
<ul role="list">
{{ range $items -}}
{{- $fields := split . "\n " -}}
{{- $src := index $fields 0 }}
{{- $alt := index $fields 1 }}
{{- $cap := index $fields 2 }}
{{ with $src -}}
<li>
<figure>
<img src="{{ . }}" {{ with $alt }}alt="{{ . }}"{{ end }} />
{{ with $cap -}}
<figcaption>{{ . }}</figcaption>
{{ end -}}
</figure>
</li>
{{ end -}}
{{ end -}}
</ul>
Checking for CRLF and stripping leading and trailing lines seems like a good move though.
If you use functions like Unmarshall or some such you could probably actually use YAML and decode it into a Hugo variable.
Oh that’s clever! I’ll look into that, probably a lot more robust than the regex I’m doing on it now, thanks.