# How to render math equations properly with KaTeX

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}$$


Produces the following:

Neither matrices nor aligned environments work properly. Is this because of Goldmark rendering?

I’m using the binario template (can’t post links as a new user sorry) and am happy to share any other files when requested.

Yes. You can determine what’s happening by viewing the browser source.

### Example 1

markdown

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


rendered

<p>$$\underbrace{a}<em>{b} - \underbrace{c}</em>{d}$$</p>


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 &amp; b \ c &amp; 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

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.