Computer Science
Algorithm
Data Processing
Digital Life
Distributed System
Distributed System Infrastructure
Machine Learning
Operating System
Android
Linux
Tizen
Windows
iOS
Programming Language
C++
Erlang
Go
Scala
Scheme
Type System
Software Engineering
Storage
UI
Flutter
Javascript
Virtualization
Life
Life in Guangzhou (2013)
Recent Works (2013)
东京之旅 (2014)
My 2017 Year in Review (2018)
My 2020 in Review (2021)
十三年前被隔离的经历 (2022)
A Travel to Montreal (2022)
My 2022 in Review (2023)
Travel Back to China (2024)
Projects
Bard
Blog
Jekyll Plugin to Load Asciinema Recordings Locally (2023)
RSS Brain
Scala2grpc
Comment Everywhere (2013)
Fetch Popular Erlang Modules by Coffee Script (2013)
Psychology
耶鲁大学心理学导论 (2012)
Thoughts
Chinese
English

Jekyll Plugin to Load Asciinema Recordings Locally

Posted on 24 Sep 2023, tagged JekyllBlogcommand lineAsciicast

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!