How to make a like counter on a static site, linked to Mastodon
Associating a mastodon post with a blog post
The Pelican static site generator uses Jinja to fill in files provided by the theme in use with variables. These variables come from plugins, pelican settings, and article metadata. Pelican allows any arbitrary metadata to be passed from an article, which we shall use to add a mastodon_link
item, which will contain a post such as https://emacs.ch/@crmsnbleyd/111701273563278029.
The HTML template in question
{
Not every post will have an associated mastodon link,
and I want other people to be able to use my
theme as is
(and they might not wish to use this 'like' counter),
so we put the HTML needed to render the favourites inside an if
block.
The likes container has a class hidden-without-js
which has the attribute display: none;
.
This makes the item not render at first.
We will use javascript later to make it visible if we are successful in our endeavour of pulling the latest number of likes from the link.
This also has the effect of not showing it at all for users with JS disabled, exhibiting graceful degradation.
We will also add some text for browsers and screenreaders which cannot show the icon (after loading the likes, through JS). The "visually hidden" class is from an article on a11yproject.
The a
element with id "post-likes" will contain the likes that we fetch. It is empty for now.
Here's the program in all its glory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
Try liking the post...
And see the little counter right under the title refresh 😊. Do let me know if any of you end up implementing something like this on your own website!