Add katex support to Hugo
Recently I decide to post some math notes on the blog, so here is how to add math formula rendering support to hugo. Actually it’s as simple as adding several lines to Hugo’s theme file.
§ UPDATE
as of 07.2025 this blog no longer uses client side katex javascript. Thanks to Hugo’s build-time Katex/MathML rendering support, math is now static.
See Ross A. Baker’s write-up for Hows (Thank you!!!)
https://rossabaker.com/configs/website/build-time-math-rendering-in-hugo-with-katex/
this link is my main reference but I need a little mod.
Katex by defaults uses double dollars $$ as delimiter no matter it is inline formular or block. However I want to use $ as inline delimiter and $$ for block,
since besides Hugo I’m using a vim-markdown preview plugin, which uses different delimiter for inline and block rendering.
Here is how to do it.
§§ 0. Simpler approach
simply put the following lines into the header partial. In most Hugo themes it is theme/layouts/partials/header.html
|
|
before the </header> tag.
§§ 1. Smarter approach
We want to:
- load katex and render page only when explicitly specified.
- modify katex delimiter as mentioned before.
1.0 Add partials to hugo theme
Add a partial file to the theme, z.B. theme/layouts/partials/katex.html
|
|
1.1 Modify footer partial
Add the following lines in the footer partial (in most cases footer.html) right before the <\body> tag.
{{ if .Params.katex}}{{ partial "katex.html" . }}{{ end }}
This will load katex.html only when the katex parameter in the front matter is set to true. Then katex.html partial will call renderMathElement function to render the body.
Here is a testing markdown file
1.2 Modify archetypes file
It works! Now we need to add katex and markup parameters to the front matter automatically when creating a new post file.
simply modify site/archetypes/defult.md like:
/post/hugo_katex_support