Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Server-side KaTeX rendering for Jekyll
require 'execjs'
module Katex
class << self
JS_FILENAME = 'vendor/katex/katex.min.js'
JS_CTX = ::ExecJS.compile(
INLINE_REGEX = /\\\((.*?)\\\)/m.freeze
DISPLAY_REGEX = /\\\[(.*?)\\\]/m.freeze
def process(text, macros)
.gsub(INLINE_REGEX) { render_inline($1, macros) }
.gsub(DISPLAY_REGEX) { render_display($1, macros) }
def render_inline(text, macros)'katex.renderToString', text, macros: macros)
def render_display(text, macros)'katex.renderToString', text, macros: macros, displayMode: true)
pre_render_task = lambda { |doc, _|
if['katex'] &&['katex']['enabled']
doc.content = Katex.process(doc.content,['katex']['macros'] || [])
Jekyll::Hooks.register(:posts, :pre_render, &pre_render_task)
Jekyll::Hooks.register(:pages, :pre_render, &pre_render_task)
layout title date katex
Server-side KaTeX rendering for Jekyll
enabled macros

Server-side KaTeX rendering for Jekyll


Pre-rendering math equations requires work on the site administrator's part, but will make your web pages load much faster. Replacing MathJax with KaTeX will also speed up math rendering.

Include this file (katex.rb) in your Jekyll site's _plugin directory, and Jekyll will load it "automagically."

This plugin depends on two things:

  • ExecJS. Make sure gem 'execjs' is included in your Gemfile. Read the ExecJS documentation and make sure you have a JavaScript runtime installed.

  • KaTeX. Make sure you have a release of KaTeX downloaded somewhere in your project folder. Replace the Katex::JS_FILENAME constant with the location of your copy of katex.min.js. Make sure you include the KaTeX stylesheets and web fonts in your HTML pages. It is not necessary to include any JavaScript on your pages to use pre-rendered KaTeX. See the KaTeX documentation for more information.


Make sure the katex.enabled flag in your posts' YAML front matter is set to true, like in this document. Read the raw document if this is unclear. You can use katex.macros to create macros. In this document, \compose is defined as \circ. See the KaTeX documentation for available commands.

This plugin parses inline math with these delimiters: \( e = mc^2 \), and display-style math with these delimiters:

\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]

It does not support the $x$ or $$x$$ notation. This can be changed, however, by updating the regex constants in the Katex module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment