So, i had this planned for a while to add some more math content to this blog.

Mostly for the content I do in french, where I do a lot of school related content for the kids but also for here, in english, where I will likely need it later when adding content about recommender system and other ML topics.

Anyway, figured out that Latex is the way to go usually when you want to do some maths in a paper, and well, turns out there is a library for this name Katex and it’s super simple to integrate in Hugo.

\[OPT(i) = \begin{cases}B[k - 1, w], \quad \text{If w < }w_k \\ max{B[k-1, w], b_k + B[k - 1, w - w_k]}, ; \quad \text{otherwise} \end{cases}\]

which is in code

1
    $$OPT(i) = \begin{cases}B[k - 1, w], \quad \text{If w < }w_k \\\ max{B[k-1, w], b_k + B[k - 1, w - w_k]}, \; \quad \text{otherwise}$$

Note that somehow I had to add an extra `\` before the max, in order for the formating to work fine. Somehow was refered in this issue.

So, how to set this up, well I actually followed the tutorial in the help of PaperMod here

  • Step 1 : Add a partial for math.html In /layouts/partials/math.html insert the following code:
1
2
3
4
<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>

Basically setting up the javascript you need to get katex to work.

  • Step 2 : Insert the call to the partial in the extend_head.html partial file.

It is the file which will had the code you created in the partial maths to <head> section of the page.

And since you do not want to javascript of katex to load for every page but only if the page has some Maths in it, so you add a conditional tag math: true

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

That’s it, you’re done!

Note: if you are using ox-hugo for writing your post in emacs orgmode, you need to add the custom math property using

1
:EXPORT_HUGO_CUSTOM_FRONT_MATTER: :math true