Issue: When using a non-modified hugo template with KaTeX, the math equations do not render properly.

How to replicate the issue: KaTeX can be imported following this guide. The latest KaTex npm can be found on jsdelivr

A full list of features of KaTeX can be seen from the official website (Supported Functions · KaTeX) and they render properly.

The markdown below:

---
title: "My First Post"
date: 2022-10-17T22:45:36+11:00
draft: false
math: true
---
This is a post about latex.
An equation:
$$\int_{-\infty}^{\infty} e^{-x^2} dx$$. <!-- works -->
inline example: $\sum_{i = 0}^N 2i = y$ <!-- works -->
One overbrace:
$${a}^{b} - \overbrace{c}^{d}$$ <!-- works-->
Two overbraces:
$$\underbrace{a}_{b} - \underbrace{c}_{d}$$ <!--does not work -->
None of these below works properly:
$$
\begin{aligned}
equation &= 16 \\
other &= 26 + 13
\end{aligned}
$$
$$
\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
$$

See the em element? That’s due to the pair of underscores in the markdown.

fix (escape first underscore)

$$\underbrace{a}\_{b} - \underbrace{c}_{d}$$

Example 2

markdown

$$
\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
$$

rendered

<p>$$
\begin{pmatrix}
a & b \
c & d
\end{pmatrix}
$$</p>

At the end of the third line the two backslashes were reduced to a single backslash, because in markdown a backslash escapes the following character.

fix (escape the escape character)

$$
\begin{pmatrix}
a & b \\\
c & d
\end{pmatrix}
$$

Alternative

To prevent Hugo from rendering to HTML before KaTex renders the math, use a shortcode or code block render hook. Here’s a small test site that demonstrates both:

git clone --single-branch -b hugo-forum-topic-40998 https://github.com/jmooring/hugo-testing hugo-forum-topic-40998
cd hugo-forum-topic-40998
hugo server