Math Typesetting

A brief guide to setup MathJax

Mathematical notation in a Hugo project can be enabled by using third party JavaScript libraries.

Setup MathJax

Create a file named mathjax.html in your theme directory of …/themes/[theme_name]/layouts/partials/.

Add the code to mathjax.html as the following:

代码是用来渲染LaTeX数学公式的JavaScript代码。它使用了MathJax库,用于在网页中呈现漂亮的数学公式。代码定义了MathJax的配置,并加载了MathJax库。

{{ if .Params.math }}
<script>
  MathJax = {
    tex: {
      inlineMath: [["$", "$"], ['\\(', '\\)']],
      displayMath: [["$$", "$$"], ["\\[", "\\]"]]
    },
    svg: {
      fontCache: "global"
    },
  };
</script>

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>

<script 
  type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
{{ end }}

Next, open the file …/themes/[theme_name]/layouts/partials/baseof.html and add the following line just before the closing </head> tag:

{{ partial "mathjax.html" . }}

Finally, add math: true to the YAML frontmatter of any pages containing math markup.


Setup KaTeX

In this example we will be using KaTeX

  • Create a partial under /layouts/partials/math.html
  • Within this partial reference the Auto-render Extension or host these scripts locally.
  • Include the partial in your templates like so:
{{ if or .Params.math .Site.Params.math }}
{{ partial "math.html" . }}
{{ end }}
  • To enable KaTex globally set the parameter math to true in a project’s configuration
  • To enable KaTex on a per page basis include the parameter math: true in content files

Note: Use the online reference of Supported TeX Functions

Examples

Block math: $$ \varphi = 1+\frac{1} {1+\frac{1} {1+\frac{1} {1+\cdots} } } $$