Math typesetting, or rendering LaTeX, in Hugo is not a hard task. We have two popular alternatives. First one is mathjax, I was using it before with jekyll. The other popular library for math typesetting is KaTeX. Since it’s faster, this time I’ll go with KaTeX.
Implementing these libraries is pretty straightforward. We just need to include them in the <head>
section. Yet, we don’t want them to load for every page, only if it’s required.
$$f(a) = \frac{1}{2\pi i} \oint\frac{f(z)}{z-a}dz$$
- Create a partial template and use the code below.
/layouts/partials/helpers/katex.html
.
The first line is the CSS, the second one is the javascript file. The third line is the auto render extension. Auto-render extension is required to render math elements inside text.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/contrib/auto-render.min.js" onload="renderMathInElement(document.body);"></script>
Don’t just copy-paste this one. It’s using version 0.12 which is the latest version when I’m typing this blog post. You may want to see if there is an update.
- Include the partial in the head section. This is
/layouts/partials/head.html
for me.
{{ if .Params.math }}{{ partial "helpers/katex.html" . }}{{ end }}
- Use the parameter math in the front-matter if you want to use the library in that post/page.
---
math: true
---
- If you want inline equations, you should add the following too.
<script>
document.addEventListener("DOMContentLoaded", function() {
renderMathInElement(document.body, {
delimiters: [
{left: "$$", right: "$$", display: true},
{left: "$", right: "$", display: false}
]
});
});
</script>
This will provide inline equations with single dollar signs. $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$
, $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$.
Have fun!