Goal

I want to write Latex equations inline in my content markdown and have Hugo compile to equations that show up on my webpage.

Step by Step Solution

Good news – this possible in Hugo. But it took me awhile to piece it all together, so I’m putting the solution here for others.

  1. Add mathjax to HTML footer. We will do this by adding this snippet to layouts/partials/footer.html:
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
  1. Install pandoc on your computer so that Hugo can use it to compile the markdown to HTML.

  2. Let the Hugo compiler know to convert the markdown file using pandoc by adding the correct markup key/value pair to the “front matter” of your content markdown:

---
title: "Weighted MAPE"
date: 2013-01-05T21:03:51-08:00
draft: false
markup: pdc
<other stuff>
---
  1. Write centered Latex equations in your markdown demarcated by double $$:
God said:
$$
\begin{eqnarray}
\nabla \cdot \vec{E} &=& \frac{\rho}{\epsilon_0}\\
\nabla \cdot \vec{B} &=& 0 \nonumber \\
\nabla \times \vec{E} &=& - \frac{\partial B}{\partial t} \nonumber \\
\nabla \times \vec{B} &=& \mu_{0}\vec{J} +
\mu_{0}\epsilon_{0}\frac{\partial E}{\partial t}
\end{eqnarray}
$$
and then there was light!
  1. Write inline Latex equations in your markdown demarcated by single $:
Einstein said $E = mc^2$.
  1. Build your site with Hugo and the equations should appear and be beautiful.

God said: \[ \begin{eqnarray} \nabla \cdot \vec{E} &=& \frac{\rho}{\epsilon_0}\\ \nabla \cdot \vec{B} &=& 0 \nonumber \\ \nabla \times \vec{E} &=& - \frac{\partial B}{\partial t} \nonumber \\ \nabla \times \vec{B} &=& \mu_{0}\vec{J} + \mu_{0}\epsilon_{0}\frac{\partial E}{\partial t} \end{eqnarray} \] and then there was light!

Einstein said \(E=mc^2\).

Solution Mental Model

What’s happening here? There are actually two pieces to the solution here – MathJax and pandoc. And of course Hugo which ties it all together and generates the HTML.

When you see beautiful equations floating around the web likely MathJax is being used to render it. MathJax is Javascript magic that renders certain HTML as beautiful equations. We need the MathJax Javascript to be loaded on our pages – this is what Step 1 does. We also need to make sure the HTML that is generated by Hugo generates properly formatted MathJax HTML – this is where Pandoc comes in.

Pandoc is a magical document converter that converts between various text formats. You can learn more about it from it’s documentation here. We will be using it to convert markdown with Latex in it to HTML with MathJax in it. Step 2 installs pandoc on our system. Step 3 tells Hugo to use pandoc to compile specific markdown files to HTML rather than its default markdown to HTML compiler.

References