Jekyll Plugin to Load Asciinema Recordings Locally
Posted on 24 Sep 2023, tagged Jekyll
Blog
command line
Asciicast
Asciinema is a wonderful tool to record Linux terminal. It saves the records as a text format called Asciicast. However, it has a strong integration with its website. Especially if you want to embed the recordings into the web page use some simple JS code like this:
<script src="https://asciinema.org/a/14.js" id="asciicast-14" async></script>
You need to share the recordings to Asciinema’s website and need to link an account with the recordings, otherwise they will be deleted after 7 days, which I just found out yesterday. I don’t want my blog to rely on some third party website for core content, so I need a way to load the recordings from my website itself.
Lucky, the Asciinema Javascript player is open source and support to load recordings from a url out of box. First you need to import the CSS:
<link rel="stylesheet" type="text/css" href="/asciinema-player.css" />
This is no big deal since this can be put in Jekyll’s template. Then you need some JS code like this:
<div id="demo"></div>
...
<script src="/asciinema-player.min.js"></script>
<script>
AsciinemaPlayer.create('/demo.cast', document.getElementById('demo'));
</script>
It’s a little bit too much for embedding a terminal recording in a blog. However, with the powerful Jekyll plugin system, We can write a plugin to make it simpler so that we can just use a tag to include it:
{% asciicast <id> %}
Here is the implementation, it’s also in my blog’s Github repo:
module Jekyll
class RenderAsciicastTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text.strip
end
def render(context)
"<div id=\"cast-#{@text}\"></div>" \
'<script src="/static/js/asciinema-player.min.js"></script>' \
"<script>AsciinemaPlayer.create('/static/asciicasts/#{@text}.cast', document.getElementById('cast-#{@text}'), {rows: 10, autoPlay: true});</script>"
end
end
end
Liquid::Template.register_tag('asciicast', Jekyll::RenderAsciicastTag)
It will find the recordings under /static/asciicasts/{id}.cast
and load from there.
Put this file under _plugins
and happy hacking!