I am trying to create a short code where I pass URLs and to a video template. I need to pass the URL to the src attribute but the video’s type to the type attribute(s) don’t necessarily need to be passed in as arguments, they can be stored as fixed values. I am able to range through my URLs but I’m stuck on how to simultaneously get the right type attribute into the loop. I’m sure I’m missing something simple here, but I’m at a loss…
In my case I want to pass in the URLs in a specific order (webm, mp4) and I need their type attributes to match.
Please forgive, I misread your question. Both formats will have the same URL except the portion /q_auto,vc_vp9/ That is where they would differ slightly
I like this a bit better. The param names for the URLs are irrelevant, but will be sorted alphabetically to determine the order of the source elements with the video element.
{{< video
v1="https://example.org/shared/samples/quickstart.mp4"
v2="https://example.org/shared/samples/quickstart.webm"
class="foo"
>}}
{{- $sources := slice }}
{{- range .Params }}
{{- if in (slice ".mp4" ".webm" ".ogv") (path.Ext .) }}
{{- $sources = $sources | append . }}
{{- end }}
{{- end }}
{{- with $sources -}}
<video controls {{- with ($.Get "class") }} class="{{ . }}" {{- end }}>
{{- range . }}
<source src="{{ . }}" type="video/{{ path.Ext . | strings.TrimPrefix "." }}">
{{- end }}
</video>
{{- else }}
{{- warnf "The %q shorcode was called without any sources. See %s" .Name .Position }}
{{- end -}}
The param names for the URLs are irrelevant, but will be sorted alphabetically to determine the order of the source elements with the video element.
With this:
{{< video
v1="https://example.org/shared/samples/quickstart.mp4"
v2="https://example.org/shared/samples/quickstart.webm"
class="foo"
>}}
… the mp4 will be first
With this:
{{< video
v2="https://example.org/shared/samples/quickstart.mp4"
v1="https://example.org/shared/samples/quickstart.webm"
class="foo"
>}}
… the webm will be first (v1 sorts alphabetically before v2).
Within the shortcode template, .Params is a map of the parameters that you pass to it. And maps (aka dictionaries), unlike slices (aka arrays), are not ordered. But when you range (loop) through a map, the keys are ordered alphabetically.
This is great! More than I could have asked for. Big thanks @jmooring!
One thing I’d like to highlight, and this is a small quibble; Is that I do care about the order of the video formats, and do want them ordered w/ the webm to come first and then subsequent formats as fall-backs. Again I refer to MDN: Web video codec guide - Web media technologies | MDN
I will stress that I agree the shortcode should determine the ordering, not the content author.