I often want to link to social and other types of web-based media in my Sphinx documentation and blog. Rather than embedding it all in custom HTML code, I decided to write a little wrapper to turn it into a directive.
It’s called {socialpost}
, and it works with Twitter, Mastodon, and YouTube links.
How it works¶
Here’s a brief description of how this directive works:
Parse the directive content (the thing that comes after
{socialpost}
, e.g.https://twitter.com/choldgraf/status/1564614538309390345
)Do some basic pattern matching to decide if it is Twitter / Mastodon / YouTube
Parse the URL for the proper unique identifier for the post (e.g. above it is
1564614538309390345
)Use an embed template that embeds this identifier into each service. E.g., for Twitter it is:
<blockquote class="twitter-tweet"><p lang="en" dir="ltr"> <a href="https://twitter.com/choldgraf/status/1564614538309390345">Tweet from @choldgraf</a> </blockquote>
This is all wrapped up in a
Directive
object that outputs an HTMLraw
node so I can pass through raw HTML.Load any necessary JS files if this directive is detected on a page. This is done with an
html-page-context
event.I then connected them both to Sphinx in my site’s
conf.py
setup function.