Selecting the best available social meta data image in Hugo

Here’s a snippet of Hugo template language that I use to try and select the best social meta data image for each page on a static site:

{{ if isset .Params "meta_image" }}
    <meta property="og:image" content="{{ .Params.meta_image | absURL }}"/>
    <meta name="twitter:image" content="{{ .Params.meta_image | absURL }}">
    <link rel="image_src" href="{{ .Params.meta_image | absURL }}"/>
    <meta itemprop="image" content="{{ .Params.meta_image | absURL }}">
{{ else if (.Resources.ByType "image") | len }}
    {{ $firstImage := index (.Resources.ByType "image") 0 }}
    <meta property="og:image" content="{{ $firstImage.Permalink }}"/>
    <meta name="twitter:image" content="{{ $firstImage.Permalink }}">
    <link rel="image_src" href="{{ $firstImage.Permalink }}"/>
    <meta itemprop="image" content="{{ $firstImage.Permalink }}">
{{ else }}
    <meta property="og:image" content="{{"/img/default-image.png" | absURL }}"/>
    <meta name="twitter:image" content="{{"/img/default-image.png" | absURL }}">
    <link rel="image_src" href="{{"/img/default-image.png" | absURL }}"/>
    <meta itemprop="image" content="{{"/img/default-image.png" | absURL }}">
{{ end }}

First it tries using a meta_image key in the page’s frontmatter, then the first image resource if one is available, and finally falls back to a default global meta image if neither of those are present.

I use this on various static Hugo sites, including Moment Wall Art, Kensio Software and the static section of Chinese Boost.

Tech mentioned