DZHG  / How to Add LaTeX Support in Hugo

hugo doesn’t support LaTex natively. LaTex is very useful and essential for writing math related content.

I run across KaTex. It’s a LaTex renderer in JavaScript. It has an extension to render all math content automatically. The basic idea is to inlude KaTex in the pages generated by hugo and render all math content with the auto-render extension.

Hook to Existing Theme

Usually, we all use a 3rd party theme. For example, this site is using hyde. You might have to modify the theme you use to include KaTex. Fortunately, hyde has a hook in theme/hyde/layouts/partials/head.html:

  {{ partial "hook_head_end.html" . }}

hook_head_end.html is simply an empty file in hyde theme. It’s a hook that can be used to customize the page head section. We can just create a hook_head_end.html in layouts/partials (in the site folder, not in the theme folder):

Now, I switched to diary theme. The only change is I have to rename hook_head_end.html to extended_head.html.

{{ if .Params.katex}}{{ partial "katex.html" . }}{{ end }}

Create Partial for KaTex

Then, create a katex.html file and follow the guide adding below content:

<link rel="stylesheet" href="" integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" crossorigin="anonymous">

<!-- The loading of KaTeX is deferred to speed up page rendering -->
<script defer src="" integrity="sha384-g7c+Jr9ZivxKLnZTDUhnkOnsh30B4H0rpLUpJ4jAIKs4fnJI+sEnkvrMWph2EDg4" crossorigin="anonymous"></script>

<!-- To automatically render math in text elements, include the auto-render extension: -->
<script defer src="" integrity="sha384-mll67QQFJfxn0IYznZYonOWZ644AWYC+Pt2cHqMaRhXVrursRwvLnLaebdGIlYNa" crossorigin="anonymous"

Update Front Matter

As we enable the partial based on a parameter .Params.katex. We can set katex: true in page’s front matter:

title: "How to Add LaTeX Support in Hugo"
katex: true

Write LaTex content

The default display mode delimiters are $$ or \\[ and \\]. For example:

$$\sum_{x=1}^5 y^z$$

$$\sum_{x=1}^5 y^z$$

\\[\int_a^b f(x)\\]

\[\int_a^b f(x)\]

Inline mode delimiters are \\( and \\). For example: \\(e = mc^2\\) \(e = mc^2\).


We can easily extend hugo for rendering LaTex. In this post, I used KaTex for LaTex parsing.

  1. Create a partial to hook KaTex into head of pages
  2. Create a partial to actual include the JavaScript and CSS files (with the auto-render extension)
  3. Update front matter to enable KaTex

After that, we can start writing LaTex on our web pages.