How to include KaTeX 0.16 in Hugo (LaTeX rendering)
This post shows how to include the latest version of KaTeX (0.16) in Hugo for rendering LaTeX math. We don’t include it from a CDN mostly for GDPR reasons, but also because it’s faster to load it from the local server.
We will include katex.min.js
, auto-render.min.js
, katex.min.css
from the assets
folder and fonts
from the static
folder (so Hugo adds the entire directory).
mkdir -p assets/js assets/css static/js static/css
cd assets/js
ln -s ../../node_modules/katex/dist/katex.min.js katex.min.js
ln -s ../../node_modules/katex/dist/contrib/auto-render.min.js auto-render.min.js
cd ../..
cd assets/css
ln -s ../../node_modules/katex/dist/katex.min.css katex.min.css
cd ../..
cd static/css
ln -s ../../node_modules/katex/dist/fonts fonts
cd ../..
Now create themes/your-theme/layouts/partials/katex.html
:
<!-- Include library -->
<link rel="stylesheet" href="{{ (resources.Get "css/katex.min.css").RelPermalink }}" />
<script defer src="{{ (resources.Get "js/katex.min.js").RelPermalink }}"></script>
<!-- Include auto-render extension & render all KaTeX formulae !-->
<script defer src="{{ (resources.Get "js/auto-render.min.js").RelPermalink }}" onload="renderMathInElement(document.body);"></script>
In themes/your-theme/layouts/partials/footer.html
, conditionally include the partial:
<!-- Include KaTeX if enabled in post-->
{{ if .Params.katex }}
{{ partial "katex.html" . }}
{{ end }}
Then, in your post .md
file, set
katex: true
in the frontmatter to enable KaTeX rendering.
Now you can add a formula such as
$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$
to your post to see it rendered by KaTeX:
$$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$