Instantly share code, notes, and snippets.

@jackwillis /katex.rb
Last active Jan 23, 2018

Embed
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(File.read(JS_FILENAME))
INLINE_REGEX = /\\\((.*?)\\\)/m.freeze
DISPLAY_REGEX = /\\\[(.*?)\\\]/m.freeze
def process(text, macros)
text
.gsub(INLINE_REGEX) { render_inline($1, macros) }
.gsub(DISPLAY_REGEX) { render_display($1, macros) }
end
def render_inline(text, macros)
JS_CTX.call('katex.renderToString', text, macros: macros)
end
def render_display(text, macros)
JS_CTX.call('katex.renderToString', text, macros: macros, displayMode: true)
end
end
end
pre_render_task = lambda { |doc, _|
if doc.data['katex'] && doc.data['katex']['enabled']
doc.content = Katex.process(doc.content, doc.data['katex']['macros'] || [])
end
}
Jekyll::Hooks.register(:posts, :pre_render, &pre_render_task)
Jekyll::Hooks.register(:pages, :pre_render, &pre_render_task)
layout title date katex
post
Server-side KaTeX rendering for Jekyll
2017-10-24
enabled macros
true
\compose
\circ

Server-side KaTeX rendering for Jekyll

Installation

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.

Usage

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