Add katex support to Hugo

Recently I decide to post some math notes on the blog, so here is how to add math formula rendering support to hugo. Actually it’s as simple as adding several lines to Hugo’s theme file.

this link is my main reference but I need a little mod.

Katex by defaults uses double dollars $$ as delimiter no matter it is inline formular or block. However I want to use $ as inline delimiter and $$ for block, since besides Hugo I’m using a vim-markdown preview plugin, which uses different delimiter for inline and block rendering.

Here is how to do it.

0. Simpler approach

simply put the following lines into the header partial. In most Hugo themes it is theme/layouts/partials/header.html

<link rel="stylesheet" href="" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">

<!-- The loading of KaTeX is deferred to speed up page rendering -->
<script defer src="" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>

<!-- To automatically render math in text elements, include the auto-render extension: -->
<script defer src="" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"

before the </header> tag.

1. Smarter approach

We want to:

  • load katex and render page only when explicitly specified.
  • modify katex delimiter as mentioned before.

1.0 Add partials to hugo theme

Add a partial file to the theme, z.B. theme/layouts/partials/katex.html

    <link rel="stylesheet" href="">
    <script src=""></script>
    <script src=""></script>

              delimiters: [
                  {left: "$$", right: "$$", display: true},
                  {left: "\\[", right: "\\]", display: true},
                  {left: "$", right: "$", display: false},
                  {left: "\\(", right: "\\)", display: false}

1.1 Modify footer partial

Add the following lines in the footer partial (in most cases footer.html) right before the <\body> tag.

{{ if .Params.katex}}{{ partial "katex.html" . }}{{ end }}

This will load katex.html only when the katex parameter in the front matter is set to true. Then katex.html partial will call renderMathElement function to render the body.

Here is a testing markdown file

title: "katex_test"
date: 2020-05-28T21:22:48+02:00
katex: true
draft: false

this is an inline form .. $x^2 + y^2 = 1$

this is a block

$$\sum_{\mathclap{1\le i\le j\le n}} x_{ij}$$

1.2 Modify archetypes file

It works! Now we need to add katex and markup parameters to the front matter automatically when creating a new post file. simply modify site/archetypes/ like:

title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
katex: false
draft: true