As I’m using Hugo static site generator with PaperMod theme, I noticed that the Latex math equations in the markdown content/posts files do not render as expected.

After some digging in the theme source code I found out there’s no Latex based library being called out during the site building process.

Which explains why something like the below doesn’t render:

$$\sum_{n=1}^{k} \frac{1}{n^2} = \frac{\pi^2}{6}$$

When in a perfect world it supposed to render like:

$$\sum_{n=1}^{k} \frac{1}{n^2} = \frac{\pi^2}{6}$$

To solve this you have to include a Latex parsing library into your Hugo theme.

Latex/Katex

I have used Katex, which is a lightweight javascript library that can parse and render Latex math equations, it’s mainly designed to be used for online web pages with focus on performance.

You could read more about Katex on https://katex.org.

Solution

Depending on the theme you are using you have to include the following code block into the theme.

{{ if or .Params.math .Site.Params.math }}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/katex.min.css" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/katex.min.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/auto-render.min.js" crossorigin="anonymous"
    onload="renderMathInElement(document.body);"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            renderMathInElement(document.body, {
                delimiters: [
                    {left: "$$", right: "$$", display: true},
                    {left: "$", right: "$", display: false}
                ]
            });
        });
    </script>
{{ end }}

You could create a math.html file in the partials folder and then call that file into your header.

Or in my case, using the PaperMod theme, I’ve inserted this code into partials/extend_head.html which is being called into the partials/head.html file.

Now this included library is in if condition, so to enable/disable the library you have two options.

Add math: true in your config file under the params. And this can enable or disable the library on the whole site.

However, if you enable it that way, then you will end up calling the library on every post regardless if there are Latex equations or not in the content. And this can add unnecessary content to download while browsing the site.

So in my experience the best way is to enable it only on the posts that contains Latex equations, and disable it on everything else.

To do so, add math: false In the frontmatter of all your posts/markdown files. And on the posts that have Latex equations you’ll have to add it as math: true.