Semantic Web for Twitter

1st April 2018

Twitter use the Semantic Web. More specifically they use RDFa markup to define Twitter Cards, which they use to make your website look good when someone tweets it. In this post I'll show you how to include this in a Flask blog application with a Jinja2 template.

Semantic Web for Twitter with Twitter Graph

I’m going to assume you have some back-end storing your blog posts with all the data fields you’ll need that you pass through to your template. This would be what you pass in to your template already to populate it with the title, date, content etc.

Twitter look for Twitter Card data encoded in RDFa, which means the data will be added to the HTML content on the normal page. You can add the additional tag attributes to the appropriate elements in the body of your HTML, however Twitter Card recommend using meta tags in the head. The advantage of this approach is that they are easier for you to read and update.

This template is for my Twitter Card meta data. You can create a file in your apps templates: templates/includes/ogmeta.html, paste the code in there and adjust as needed. This template is intended for use in a blog, you can check the terms you wish to use and adapt it from the documentation at Twitter Card.

<!-- Open Graph Data -->
<meta name=”twitter:card” content=”summary” />
<meta property="twitter:url" content="{{ post.path }}" />
<meta property="twitter:title" content="{{ post.title }}" />
<meta property="twitter:description" content="{{ post.description }}" />
<meta property="twitter:image" content="{{ post.image }}" />
<meta property="twitter:image:alt" content="{{ post.title }}" />
<meta property="twitter:creator" content="@paulbrownmagic" />

RDFa uses namespace prefixes, which is what lets us write twitter:title instead of the full URI that identifies a Twitter Card title. However, Twitter breaks this rule and does not define its terms at any URI. Twitter Card has also being designed to work with some Open Graph terms, you can find more information in their docs and see an example of Open Graph with Jinja2 in a previous blog post called Semantic Web for Facebook.

You can pretty much copy and paste from this blog post and make it easy for Twitter to parse your blog or webpage without needing to become an expert in all things Semantic Web.

Until next time, happy coding.

Post Tags

All Tags

LIFE IS better when we share.