How to test for optional shortcode parameters in Hugo

Hugo Shortcodes are a great way to create reusable snippets that can be embedded directly inside your content. A common need when using a shortcode is to check for the existence of an optional parameter on the shortcode invocation in order to customise the output of the shortcode. This task can be achieved through the isset function as shown below:

{{ $loading := "" }}
{{ if isset .Params `lazy` }}
  {{ $loading = "loading=lazy" }}
{{ end }}

<img {{ $loading | safeHTMLAttr }}>

The above shortcode may be used as follows:

{{< image lazy >}}

If the lazy parameter is included in the shortcode (as above), the loading=lazy attribute will be set in the shortcode output. Otherwise, it would be omitted from the output.

Thanks for reading, and happy coding!