I am continuing to clean my Hugo site. Going over old posts, I found one on explaining artificial neural networks that included a bunch of equations based on screenshots from my master’s thesis. Now, with the help of CoPilot, I have implemented proper equation support on my Hugo site.

KaTeX to the rescue

I am used to writing my academic texts using LaTeX, an advanced typesetting library where you write code and compile it to a PDF (or something else). One of the benefits of LaTeX is its advanced support for typing equations (and many other features). However, until recently, it wasn’t so easy to write equations in HTML.

Now, I discovered KaTeX is a fast, lightweight JavaScript library for typesetting mathematics on the web: it supports a large subset of LaTeX, renders math as HTML/CSS (and can emit MathML), and focuses on high-quality, accessible output with much better client-side performance than traditional TeX-based renderers.

Setting it up

Adding KaTeX to my Hugo blog required adding only a small code snippet to the site <head> (via the PaperMod theme’s head.html partial). This code loads KaTeX from the jsDelivr CDN and calls the renderMathInElement(document.body, ...) auto-render function with the common delimiters $...$ for inline math and $$...$$ for display math. KaTeX then finds math snippets in the page and renders them to HTML/CSS.

Only two files changed:

  • layouts/partials/extend_head.html — loads KaTeX CSS/JS and initializes the auto-renderer
  • hugo.tomlmarkup.goldmark.renderer.unsafe = true is set so math and certain HTML can render

Two writing modes

You can write math inside paragraphs by using $...$, for example $\\Delta w_i = \\eta\\,\\delta\\,x_i$, which will render as $\Delta w_i = \eta,\delta,x_i$.

For full equations, you can use $$...$$, which will render centered on its own line:

$$ w_i^{(n+1)} = w_i^{(n)} + \Delta w_i $$

The syntax is similar to LaTeX, so it is easy to convert between the two. I don’t typically write much math on this blog, but it is helpful for the few posts that include equations.


Thanks to CoPilot for helping me set it up on my blog and to Grammarly for spellchecking.