Optional shortcode parameters & conditional variables assignment

Okay so I was just about to open a new topic about the very same subject. I’ll post here instead.

Hi, I’d like to have optional params in my shortcode. However, when I process this with cond, I’m getting some errors :

{{ $width := cond (gt (len .Params) 1) (.Get 1) "512" }}
{{ $quality := cond (eq (len .Params) 3) (.Get 2) "30" }}

Returns:

ERROR 2018/03/28 14:51:23 No shortcode param at .Get 1 in page posts/2018/01/projection-de-conquerir-notre-9346.fr.md, have params: [BXv4Txr9CYU]
ERROR 2018/03/28 14:51:23 No shortcode param at .Get 2 in page posts/2018/01/projection-de-conquerir-notre-9346.fr.md, have params: [BXv4Txr9CYU]

I guess that’s normal because the content of .Get 1 will be evaluated before being passed to the function. The same goes with the default function.

Is there some trick I’m unaware of, or is the following snippet the most convenient/elegant way to do the trick? My template now:

{ if eq (len .Params) 2 }}{{ .Scratch.Set "width" (.Get 1) }}{{ else }}{{ .Scratch.Set "width" "512" }}{{ end }}
{{ if eq (len .Params) 3 }}{{ .Scratch.Set "quality" (.Get 2) }}{{ else }}{{ .Scratch.Set "quality" "30" }}{{ end }}
{{ $width := .Scratch.Get "width" }}
{{ $quality := .Scratch.Get "quality" }}

I’ve found at least two other topics talking about this issue:

I think the problem is that named parameters when queried by .Get return "" if they don’t exist, while positional parameters raise an error instantly.

If everybody agrees positional params should return an empty value too (so that they can be chained with with or if to check for their existence), I will be glad to make a PR to fix this. @bep, what do you think?

1 Like