Easy social media images and markup with Hugo

Twitter Cards and Facebook’s OpenGraph provide semi-standardised markup for describing web content to social media and other aggregators.

This can be quite handy for blogs and other text content, as you can provide default information when your content is shared. This is a nice way to make sure your posts get a reasonable cover image when shared to someone’s social timeline.

Here’s the Hugo / Go HTML template I’m currently using here to add some basic sharing markup to each post as part of the HTML head:

<meta property="og:article:published_time"
      content="{{ .Date.Format "2006-01-02T15:04:05Z0700" }}" />
<meta property="og:article:author"
      content="{{ .Params.author }}" />
{{ with .Params.og_image }}
  <meta property="og:image" content="{{ . | absURL }}" />
{{ end }}

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@hughgrigg">
<meta name="twitter:creator" content="@hughgrigg">
<meta name="twitter:title" content="{{ .Title }}">
<meta name="twitter:description" content="{{ .Summary }}">
{{ with .Params.og_image }}
  <meta name="twitter:image" content="{{ . | absURL }}">
{{ end }}

Note the Params.og_image post parameter that comes from the frontmatter in the post’s markdown file, for example:

---
title: Easy social media images and markup with Hugo
date: 2020-04-19
author: Hugh Grigg
og_image: /img/2020/hugo-social-markup.png
tech:
 - HTML
 - Hugo
topics:
 - Learning
---

The absURL function ensures that a full URL is given, as this is not a href attribute, so relative paths won’t work on all platforms.


Tech mentioned