This blog is built with Hugo, using the Hello Friend NG theme developed by Djordje Atlialp. One thing that it does not support natively is equations. There are multiple ways of including equations in a statically generated site like this, so this post is as much for my future reference as anything else. The two main options available are Mathjax and KaTeX. I wanted to use \(\KaTeX\) due to its faster rendering speed, however, I did not want to change the default renderer in Hugo, Goldmark, to an alternative such as MMark (which many other posts suggest although it is deprecated). This post shows you how to accomplish this in a way that seems to work well.

Math Partial

First create a partial layout math.html in your Hugo themes folder (in this case themes/hello-friend-ng/layouts/partials/math.html). A partial allows us to import the necessary CSS and JavaScript. All this file needs to do is import the requirements so it can just consist of:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css"
    integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" crossorigin="anonymous">

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.js"
    integrity="sha384-g7c+Jr9ZivxKLnZTDUhnkOnsh30B4H0rpLUpJ4jAIKs4fnJI+sEnkvrMWph2EDg4"
    crossorigin="anonymous"></script>

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/contrib/auto-render.min.js"
    integrity="sha384-mll67QQFJfxn0IYznZYonOWZ644AWYC+Pt2cHqMaRhXVrursRwvLnLaebdGIlYNa" crossorigin="anonymous"
    onload="renderMathInElement(document.body);"></script>

Using the Math Partial

The partial which we have just required now needs to be used to render the pages which are going to contain equations. Add the following code snippet in the template which renders posts (e.g., themes/hello-friend-ng/layouts/posts/single.html):

{{ if or .Params.math .Site.Params.math }}
  {{ partial "math.html" . }}
{{ end }}

This adds a math parameter for us to choose which pages we want to use KaTeX on.

Add LaTeX to posts

Once this is done set math: true in the frontmatter of posts in which you want to include equations and you are good to go! To include an equation block include the LaTeX in double dollar signs as a delimiter on a single line. For example here is the code for a linear time series regression equation:

$$y_t = \beta_0 + \beta_1 x_t + \epsilon_t$$

Which will render as:

$$y_t=\beta_0+\beta_1 x_t + \epsilon_t$$

And to display equations inline, for example \(y_t\), surround the LaTeX with \\( \\) as a delimiter:

\\(y_t\\)

I hope this is helpful for anyone else trying to get equations to render quickly and easily in a Hugo website.