Featured image of post How to enable KaTeX (LaTeX-style math formulas) in Hugo

How to enable KaTeX (LaTeX-style math formulas) in Hugo

What is KaTeX

KaTeX is a JavaScript library for displaying LaTeX-style mathematical formulas in HTML.

Specifically, it can display formulas like the following:

$$f(x) = x^2 + x + 41$$

There seem to be other LaTeX-style math rendering libraries, but KaTeX is known for being simple and fast.

How to introduce it to Hugo

  1. Create a new layouts/partials/math.html in your Hugo folder hierarchy.

Make the contents as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css" integrity="sha384-vKruj+a13U8yHIkAyGgK1J3ArTLzrFGBbBc0tDp4ad/EyewESeXE/Iv67Aj8gKZ0" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.js" integrity="sha384-PwRUT/YqbnEjkZO0zZxNqcxACrXe+j766U2amXcgMg5457rve2Y7I6ZJSm2A0mS4" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
  renderMathInElement(
    document.body,
    {
      delimiters: [
        {left: "$$", right: "$$", display: true},
        {left: "\\[", right: "\\]", display: true},
        {left: "$", right: "$", display: false},
        {left: "\\(", right: "\\)", display: false}
      ]
    });
  });
</script>
  1. Next, add the following code to the existing file layouts/partials/extend_head.html.
1
2
3
{{ if or .Params.math .Site.Params.math }}
{{ partial "math.html" . }}
{{ end }}
  1. Now you are ready to use KaTeX.

You can enable KaTeX by adding math: true to the front matter of a page.

  1. All you have to do is write formulas in LaTeX style in the body of the page article.
1
$$ e^{i \pi} = -1 $$

If you describe it as above, it will be displayed as follows:

$$ e^{i \pi} = -1 $$

References

comments powered by Disqus