Bundle image resource question - open graph - conditional logic

I’m organising my content using Page Bundles.

My objective is to populate my Open Graph image metadata without adding another frontmatter field in an individual page .md file.

My current strategy is to have an image prefixed with “featured” in the bundle’s /images directory e.g:


I currently have this code in my default/baseof.html which works fine:

  {{ $img := (.Resources.ByType "image").GetMatch "images/*featured*" }}
  {{ with $img }}
    <meta property="og:image" content="{{ .Permalink }}">
  {{ end }}

This was generously shared by @bep in this support topic.

I want to add a conditional {{ else }} statement to generate a fallback image in the event that there is no image beginning with “featured” in the /images directory.

If I try using if instead of with I lose my context to display the featured image. I wish I knew more about hugo/go programming WRT templating and scope but I can’t figure out how to find that same image using an if statement.

Are there any gurus our there who can help a brother out?

I found a fix myself:

  {{ $img := (.Resources.ByType "image").GetMatch "images/*featured*" }}
  {{ if (.Resources.ByType "image").GetMatch "images/*featured*" }}
    <meta property="og:image" content="{{ .Permalink }}{{ $img.Name }}">
    <meta property="og:image:secure_url" content="{{ .Permalink }}{{ $img.Name }} | absURL }}"/>
    {{ else }}
    <meta property="og:image" content="http://example.com{{ .Site.Params.og_image | relURL }}"/>
    <meta property="og:image:secure_url" content="{{ .Site.Params.og_image | absURL }}"/>
  {{ end }}

This page is such a handy resource!

1 Like