Adding support for Twitter cards to Jekyll

I’ve been spending a lot more time on Twitter lately in an effort to build my profile and attract more visitors to my blog. To improve the way my content looks when it’s shared on Twitter and encourage more people to share it, I decided to add support for Twitter Cards which was actually really easy.

The documentation describes Twitter Cards as follows:

With Twitter Cards, you can attach rich photos, videos and media experience to Tweets that drive traffic to your website. Simply add a few lines of HTML to your webpage, and users who Tweet links to your content will have a “Card” added to the Tweet that’s visible to all of their followers.

Adding support for Twitter Cards was simple, thanks to the quality of the documentation. There are seven different types of Twitter Card, each suited to a particular type of content (such as photos, apps, or products). I went with the Summary Card as this is the most suitable card for blog posts.

I added the following code to _includes/head.html:

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@dgwolff">
<meta name="twitter:creator" content="@dgwolff">
{% if page.title %}
  <meta name="twitter:title" content="{{ page.title }}">
{% else %}
  <meta name="twitter:title" content="{{ site.title }}">
{% endif %}
{% if page.url %}
  <meta name="twitter:url" content="{{ site.url }}{{ page.url }}">
{% endif %}
{% if page.description %}
  <meta name="twitter:description" content="{{ page.description }}">
{% else %}
  <meta name="twitter:description" content="{{ site.description }}">
{% endif %}
{% if page.image %}
  <meta name="twitter:image:src" content="{{ site.url }}/images/posts/{{ page.image }}">
{% else % }
  <meta name="twitter:image:src" content="{{ site.url }}/images/posts/me.png">
{% else % }
  <meta name="twitter:image:src" content="{{ site.url }}/images/posts/me.png">
{% endif %}

For the Title, Description and Image variables this code will look for specific values on each page and use the site-wide defaults if these are missing.

Once you’ve added the required code to your site, you need to test it with Twitter’s Card Validator in order to activate the display of Twitter Cards for your content. I’ve read that it can take up to two weeks for Twitter to approve your site but thankfully it was instantaneous for me. Going through this validation also gives you a chance to preview what your cards will look like:

The Twitter Card Validator screen
My sample Twitter Summary Card

Looks cool right?