Turning a Param into an image

So I have this strange piece of coding:

{{ range $paginator.Pages }}
{{ $thumbCrop := $.Param "thumb-crop" }}
{{ $param_img := .Param "image" }}
{{ $fm_images := .Resources.Match $param_img }}
{{ $res_imgs := .Resources.ByType "image" }}
{{ $matches:= $fm_images | default $res_imgs }}
{{ $img := first 1 $matches }}
<div class="list-item">
    <div>
        {{ with $img }}
        {{ range . }}
        {{- $thumbHref := .Fill $thumbCrop }}
        <img src="{{$thumbHref.RelPermalink}}">
        {{ end }}
        {{ end }}
    </div>
...

It should look through all pages, look in front matter for a image param, take this image from the page’s resources, or alternatively use the first of the page resource images. I don’t like this style of coding - far too verbose, but go’s template language kind of forces this upon the uninitiated.

I’d be very thankful, for hints, how I could write this in a more concise and resource friendly way.

However, my actual problem here is, that

.Resources.Match $param_img

fails with

executing "main" at <$param_img>: invalid value; expected string

What on earth does .Param return? In the front matter it is a string for sure! How can I find out, other than to bore you with my stupid questions?

What does the parameter “image” define? :wink: According to your error message not a string.

Is is set? Did you add " around it?

It is not present on all pages, where it is, it has the right format

image: "Graphias-geral-retrabalhada-036baixa.jpg"

at least from what I can gather.

How could I add more robustness around this?

There is also the case, that there is neither a param nor a first image. I assumed, the with clause would take care of this, but what the hell, everything seems possible and it is very dark in here, even with all the friendly voices…

Well, the error pops up if you have no image set. You need to add some kind of check around the whole thing for if image exists… something like:

{{ range $paginator.Pages }}
{{ $thumbCrop := $.Param "thumb-crop" }}
{{ $param_img := .Param "image" }}
{{ $fm_images := .Resources.Match $param_img }}

{{ with $fm_images }}

{{ $res_imgs := .Resources.ByType "image" }}
{{ $matches:= $fm_images | default $res_imgs }}
{{ $img := first 1 $matches }}
<div class="list-item">
    <div>
        {{ with $img }}
        {{ range . }}
        {{- $thumbHref := .Fill $thumbCrop }}
        <img src="{{$thumbHref.RelPermalink}}">
        {{ end }}
        {{ end }}
    </div>
...

{{ end }}

I think the error comes when you call {{ $res_imgs := .Resources.ByType "image" }} and not the line before. $fm_images should just be null or empty when you call it and nothing is found.

You will have to show more code (link to repo) if that is not the case.