Template variables and image processing

I’m new to Hugo, and I can’t work out which bit of what I’ve done is wrong, so it’s difficult to search for an answer.

While hugo server was running, I put the following into a post template:

{{ $mainimg := .Page.Resources.GetMatch "mainimg.*" }}
{{ $thumb := $mainimg.Resize "400x" }}
<a href="{{ $mainimg.RelPermalink }}">
  <figure class="">
    <img src="{{ $thumb.RelPermalink }}" width="{{ $thumb.Width }}" height="{{ $thumb.Height }}">
  </figure>
</a>

and it worked perfectly.

But if I restart hugo server, or just run hugo, I get the following error:

Error: Error building site: failed to render pages: render of "page" failed: "/home/chris/projects/hugo/qs4/layouts/preview/single.html:36:27": execute of template failed: template: preview/single.html:36:27: executing "main" at <$mainimg.Resize>: can't evaluate field Resize in type resource.Resource

Can anyone give me a clue?

Perhaps you can find answers here: https://regisphilibert.com/blog/2018/01/hugo-page-resources-and-how-to-use-them/

1 Like

Looks to me, your image works on a few pages but not all of them. You should really use with or if to test for its presence before trying to resize it or reference it. :slight_smile:

That might have worked once, because Hugo live reload only works on the present page by default and this particular one had a mainimg.

1 Like

Thanks for that, Leo – that’s a useful page that I hadn’t seen before.

1 Like

Thanks Régis – your answer explains my problem exactly. I hadn’t understood that difference between a live reload and a full restart of Hugo. And although I knew about with I hadn’t thought to use it here.

And thank you for creating the page that Leo mentioned – I’ve learnt a few things from that too.

Cheers

Chris

1 Like

Most welcome!

It’s really worth reading all posts from @regis. I did the same and the sky cleared. He is also very supportive if you ask questions. Learned a lot - very much appreciated.

2 Likes