Using KaTeX in Hugo for math typesetting

Rendering latex in hugo can be achieved using KaTeX. This gives us the ability to render equations like below efficiently:

$\displaystyle\sum\limits_{i=0}^n i^3$

Steps to follow

We want to implement it in such a way that any pages that uses math typesetting can be earmarked with math: true in front-matter and then optionally katex will render the formulas given as below:

$\displaystyle\sum\limits_{i=0}^n i^3$

with:

$\displaystyle\sum\limits_{i=0}^n i^3$

  1. Create a partial template under /layouts/partials/math.html, Make sure to check for the updated version of the extension:
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.css">
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.js"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/contrib/auto-render.min.js" onload="renderMathInElement(document.body);"></script>
    

    i. If you need inline equations include the following as-well:

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        renderMathInElement(document.body, {
            delimiters: [
                {left: "$$", right: "$$", display: true},
                {left: "$", right: "$", display: false}
            ]
        });
    });
    </script>
    
  2. Include the below partial in the head section. In my case using PaperMod I had to add it to the following file layout/partials/extend_head.html:
{{ if or .Params.math .Site.Params.math }}
{{ partial "math.html" . }}
{{ end }}
  1. Use the parameter math: true in the front-matter or site parameters for enabling KaTeX in your posts.

References