In this post I want to show how you can add support for TeX so you can properly render TeX code in your Hugo blog. Chances are that you are already familiar with Hugo and with how everything works. If you are not, that’s no problem, you can simply follow this tutorial step by step. Before you start, you should check if your Hugo theme doesn’t already support TeX, else this tutorial is pretty much useless for you.

First of all, we create a file called katex.html inside the partials folder which you can find in the layouts folder. Inside it, we paste the following code:

<link rel="stylesheet" href="" integrity="sha384-RZU/ijkSsFbcmivfdRBQDtwuwVqK7GMOw6IMvKyeWL2K5UAlyp6WonmB8m7Jd0Hn" crossorigin="anonymous">
<script defer src="" integrity="sha384-pK1WpvzWVBQiP0/GjnvRxV4mOb0oxFuyRxJlk6vVw146n3egcN5C925NCP7a7BY8" crossorigin="anonymous"></script>
<script defer src="" integrity="sha384-vZTG03m+2yp6N6BNi5iM4rW4oIwk5DfcNdFfxkk9ZWpDriOkXX8voJBFrAO7MpVl" crossorigin="anonymous"

This is the auto-render extension of KaTeX, which, as the name suggests, automatically renders all of the TeX math inside a text. For more information, refer to this page.

Afterwards, we switch to the posts folder which is located inside the layouts folder as well. There we add a copy of the single.html file from the themes/YOUR-THEME/layouts/posts folder and insert the following code inside the <article> element:

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

In a nutshell, this piece of code uses the KaTeX auto-render I mentioned above to render all of the TeX Code it can find inside the blog post, assuming that the post contains the line katex: true in its front matter.

We are pretty much done and we can see that this TeX code

$$\int \frac{1}{x-2}$$

outputs the following $$\int \frac{1}{x-2}$$ which in turn shows that the KaTeX auto-render is working.


In order to automatically add the katex line inside the front matter of every blog post, we can override the current archetype of a blog post. To do so, we simply go inside the archetypes folder and add a file called Inside that file, we add the following code:

title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
toc: false
katex: false
  - untagged

If that file already exists in that folder, simply add katex: false somewhere in the front matter.

The file basically represents the front matter of every blog post we create from now on. If you are using TeX code inside your post and want to render it, simply set katex: true.

I hope you could follow this small tutorial and that you achieved the desired result.

Have a great day! 😄