Math Typesetting in Hugo

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

  1. 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/[email protected]/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"></script>

<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/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.

  1. Include the partial in the head section. This is /layouts/partials/head.html for me.
{{ if .Params.math }}{{ partial "helpers/katex.html" . }}{{ end }}
  1. Use the parameter math in the front-matter if you want to use the library in that post/page.
---
math: true
---
  1. 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!

Next Episode

published on 22.08.2020

Tags in Hugo is a default taxonomy and we don’t need any special configuration to use tags. We just enter the tags in the post’s front-matter. This can be YAML, TOML, or JSON. I’m using the YAML format, just a personal preference. […] tags: ["hugo", "tags"] …

Previous Episode

published on 06.08.2020

Search engine bots or crawlers, use two files to crawl a website more intelligently. These are robots.txt and sitemap.xml. A robots.txt file tells search engine crawlers which pages or files the crawler can or can’t request from the site. This is used mainly to avoid overloading your site with …

TAG CLOUD