Get a remote resource with its url defined in page frontmatter

Hugo and Go noob here.

This works:

layout:

{{ $featured_image := resources.GetRemote "https://example.com/some_image.jpg" }}
<img src="{{ $featured_image.RelPermalink }}">

But if I set the image URL in page frontmatter and then try to do resources.GetRemote .Params.featured_image, it doesn’t work.

content/hello-world.md:

title: Hello World
featured_image: "https://example.com/some_image.jpg""

layout:

{{ $featured_image := resources.GetRemote .Params.featured_image }}
<img src="{{ $featured_image.RelPermalink }}">

Error message:

render of "taxonomy" failed: "layouts/_default/single.html:14:14":
execute of template failed at<$featured_image.RelPermalink>:
error calling RelPermalink: error calling resources.GetRemote: Get "":
unsupported protocol scheme "" render of "term" failed: unsupported
protocol scheme ""  failed to render pages: render of "term" failed:
unsupported protocol scheme "" 

What am I doing wrong? Thank you! Any help appreciated.

I suspect that one or more of the pages rendered by this template does not have a featured_image parameter in front matter. You need to code defensively:

{{ with .Params.featured_image }}
  {{ with resources.GetRemote . }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
  {{ end }}
{{ end }}   

Even better with some error checking:

{{ with .Params.featured_image }}
  {{ with resources.GetRemote . }}
    {{ with .Err }}
      {{ errorf "%s" . }}
    {{ else }}
      <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
    {{ end }}
  {{ else }}
    {{ errorf "Unable to get remote image %s" . }}
  {{ end }}
{{ end }}
2 Likes

Thank you so much! You are right! Some pages did not have the image set. I was thinking it wouldn’t matter as I was only trying to view this one page that does have featured image set. I wasn’t realizing that hugo always builds the whole website even when running hugo server. That outermost with solved it. Thank you! :slight_smile:

Would’ve been helpful if the error message or running --debug --verbose said on which content/page the error occurs.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.