GetMatch with variable - issue

I am trying to programmatically match a resource and it works fine when I use a hard-coded string, but when I try using a variable there is an issue.

Resources file:

  - name: 1a
    title: Step 1a
    src: "img/process/01/01_explore/1a.png"
  - name: 1b
    title: Step 1b
    src: "img/process/01/01_explore/1b.png"

Template file:

                    {{ $page := .Site.GetPage "/media" }}
                    {{ $badge := .Params.badge }}
                    {{ $resA := $page.Resources.GetMatch (printf "%s*" $badge) }}
                    {{ $resB := $page.Resources.GetMatch "1a*" }}
                        {{ $resA.Title }}
                        {{ $resB.Title }}
                        {{ printf "%s*" $badge }}

$resB.Title returns the “Step 1a”, but $resA returns an error:

execute of template failed: template: processes/single.html:299:35: executing "main" at <$resA.Title>: nil pointer evaluating resource.Resource.Title

{{ printf "%s*" $badge }} returns a string as “1a*” (the same string as in the hard-coded case).

I can’t seem to understand why this is happening.

Any help is appreciated.

I got this working. I think the important thing to note, is that your resources page must be a leaf bundle:

Therefore, /media should live at content/media/index.html. If that is what you’re already doing, can you please upload a sample repo on GitHub or GitLab?

Hi and thank you for answering.
Please find a simple example (data structure is the same as the original project I am working on) here:

Due to complex HTML structure of the original templates, I can’t really embed the images inside the markdown files.

Needs to be {{ $id := $ }}

Try {{ $resource := $page.Resources.GetMatch (printf "%s" ($id|string)) }}

Well first of all, thank you for proving me wrong :innocent: :
GetMatch works fine with current implementation of the variable.
In the example I have provided there was an issue (I guess I rushed the code), which when rectified works perfectly (working copy is on a branch called “working” -->

This then tells me I need to go back and check what I did wrong in my master project - the one where this error originated from, but at least now I know that it does work.

So thank you very, very much for your input and help!

1 Like

the issue is there if I take the working code and put it in a block like so:

Any idea why this might cause it to break?

Edit: Actually it works fine while the Hugo server is running and the changes are made, but each subsequent run of the server causes the error to show up. It’s quite strange.

I’ve solved this one by not trying to match the specific resource name with the use of GetMatch, but rather load all of them using {{ $resources := $page.Resources.ByType "image" }} and then sorting them out with where command.
Ref. --> [SOLVED] Media in separate folder and accessing with Page Resources