[SOLVED] Setting a variable to one of two values in a shortcode

I’m creating a shortcode at the moment, and I have this variable, which gets the value of the first parameter:

{{ $imageName := .Get 0 }}

Ideally though, I want to get the value of a parameter named “name”, and if that parameter/value doesn’t exist, then the fallback would be to use the first parameter.

I know this isn’t actual code, but something like this:

{{ $imageName := .Get "name" or .Get 0 }}

I’ve tried to figure this out myself, but Go’s templating language hasn’t quite “clicked” for me yet, and I haven’t been able to find any clear resources for learning it as of yet.

Any help would be appreciated.


Edit: IGNORE THIS :smile:

{{if .IsNamedParams }}
{{$imageName := .Get "name"}}
{{$imageName := .Get 0}}


Does this actually work? I tried a similar problem before, but I kept getting errors of the variable ($imageName here) being undefined. It looked like the execution kept variable constrained to the if/else scope, and it wasn’t available outside of it.

There is definitely scoping issues, unfortunately. But I’m guessing that’s where Hugo’s “Scratch” functionality might come in handy? I’m going to try it later.

No, it doesn’t work. You will need to set those in Scratch as a workaround.

Sorry, it won’t work w/r/t redefining the variable, but you can use the .Get directly, at least that’s the way it’s currently being represented in the docs…


{{if .IsNamedParams}}
<img src="images/{{.Get "name"}}"/>
<img src="images/{{.Get 0}}"/>

This seems to be working for me now:

{{ if .IsNamedParams }}
    {{ $imageName := .Get "name" }}
    {{ $.Scratch.Add "imageName" $imageName }}
{{ else }}
    {{ $imageName := .Get 0 }}
    {{ $.Scratch.Add "imageName" $imageName }}
{{ end }}

{{ $imageName := $.Scratch.Get "imageName" }}

With this code in place, I can simply reference the $imageName variable, without the scoping issues.

I’ve also found a use for the default function, mentioned on this page.