Adding Twitter Cards to Hakyll Posts

Posted on April 15, 2019 by Riccardo.


By default Hakyll does not add the proper meta tags for Twitter Cards. For that reason, if we try to tweet a link to a Hakyll post, no card will be rendered. We can confirm that by using Twitter’s Card Validator:

Twitter card validator saying “Unable to render card preview”

That can be fixed with a few lines of code:

Twitter card validator showing the Twitter card with post’s cover_image, title and description

The Few Lines of Code

As explained in the docs, it’s enough to add to the head of the HTML document the following stuff:

<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@nytimesbits" />
<meta name="twitter:creator" content="@nickbilton" />
<meta property="og:url" content="" />
<meta property="og:title" content="A Twitter for My Sister" />
<meta property="og:description" content="In the early days, Twitter grew so quickly that it was almost impossible to add new features because engineers spent their time trying to keep the rocket ship from stalling." />
<meta property="og:image" content="" />

In Hakyll we can add the meta tags to templates/default.html. We just need to make sure to have them only in the post pages. To make that happen, we just check if the description key is present in the context:

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="MY_TWITTER_HANDLE" />
  <meta name="twitter:creator" content="MY_TWITTER_HANDLE" />
  <meta property="og:url" content="$url$" />
  <meta property="og:title" content="$title$" />
  <meta property="og:description" content="$description$" />
  <meta property="og:image" content="$cover_image$" />

And then in each post metadata we need to add description and cover_image:

description: Some description of my post

Support my work by tweeting this article! 🙏