How to check for returned value from .Resources.GetMatch?

I’m trying to use an image page resource for thumbnail generation. If there’s no image with such name, then fallback to another image.

{{ $thumb := .Resources.GetMatch "thumb.*" }}

{{ if not $thumb }}
    {{ $thumb := .Resources.GetMatch "0.*" }}
{{ end }}

{{ $thumb := $thumb.Resize "500x" }}

Apparently, this is not the way to do it as I don’t get the fallback image (0.jpg) if thumb.jpg is missing.

Either this is not the right way to check if $thumb contains a resource, or whatever happens inside the conditional statement is not usable outside of it.

Any tips? Thanks in advance.

Spot on. This will be fixed in Go 1.11, but until then you need to use .Scratch (search the docs).

1 Like

Thanks, I’d read something about it but thought it’s irrelevant for “custom” page variables.

For anybody interested - not sure this is the way to use .Scratch but here’s what worked for me:

{{ $thumb := .Resources.GetMatch "thumb.*" }}
{{ .Scratch.Set "thumbscratch" $thumb }}

{{ if not $thumb }}
    {{ $thumb := .Resources.GetMatch "0.*" }}
    {{ .Scratch.Set "thumbscratch" $thumb }}
{{ end }}

{{ $thumb := .Scratch.Get "thumbscratch" }}

{{ $thumb := $thumb.Resize "500x" }}

Based on the glob examples for the library that hugo uses for .GetMatch, it should be possible to replace that whole thing with:

{{ with .Resources }}
    {{ with .GetMatch "{thumb.*,0.*}" }}
        {{ $thumb := .Resize "500x" }}
        <!-- more stuff -->
    {{ end }}
{{ end }}

I like to use with as much as possible.

4 Likes

Wow, this looks so much better! And yes, it does work.