Using Katex in Hugo

KaTex allows you to show math equations like a mathematician.

Here is a summary of how I got it to work for me.

To get KaTex to work one must import their JavaScript and CSS files.

To do that one has to create a partial called ‘math.html’ that contains the following:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css"
    integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" crossorigin="anonymous">

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.js"
    integrity="sha384-g7c+Jr9ZivxKLnZTDUhnkOnsh30B4H0rpLUpJ4jAIKs4fnJI+sEnkvrMWph2EDg4"
    crossorigin="anonymous"></script>

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/contrib/auto-render.min.js"
    integrity="sha384-mll67QQFJfxn0IYznZYonOWZ644AWYC+Pt2cHqMaRhXVrursRwvLnLaebdGIlYNa" crossorigin="anonymous"
    onload="renderMathInElement(document.body);"></script>

I then incuded the partiasl in the ‘single.html’ template in the following way:

{{ define "main" }}
  {{ if or .Params.math .Site.Params.math }}
    {{ partial "math.html" . }}
  {{ end }}

    <div class="main-article">
        <hr>
        <h1>{{ .Title }}</h1>
        {{ .Content }}
    </div>

{{ end }}

I then added:

math: true

in the front matter of the Markdown file that contains the equation.

I next create the equation in KaTex format. If I wanted to show it as a block I placed two $ characters at each end of the equation, such as:

$$    $$

For example:

$$\eta_h = \frac{H_n}{H}$$

If I want to show the equation in-line with other text I enclose the equation with the following characters:

\\( \\)

For example:

This equation says it all: \(\int \frac{1}{x} dx = \ln |x|\)

And that’s all there is to it.

Update

The above method uses version 0.12.0 of KaTex. The current version is 0.15.3

The CSS and JS files for these are:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.3/dist/katex.min.css" integrity="sha384-KiWOvVjnN8qwAZbuQyWDIbfCLFhLXNETzBQjA/92pIowpC0d2O3nppDGQVgwd2nB" crossorigin="anonymous">

    <!-- The loading of KaTeX is deferred to speed up page rendering -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.3/dist/katex.min.js" integrity="sha384-0fdwu/T/EQMsQlrHCCHoH10pkPLlKA1jL5dFyUOvB3lfeT2540/2g6YgSi2BL14p" crossorigin="anonymous"></script>

    <!-- To automatically render math in text elements, include the auto-render extension: -->
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.3/dist/contrib/auto-render.min.js" integrity="sha384-+XBljXPPiv+OzfbB3cVmLHf4hdUFHlWNZN5spNQ7rmHTXpd7WvJum6fIACpNNfIR" crossorigin="anonymous"
        onload="renderMathInElement(document.body);"></script>


PLV
First Published: 3/24/2022