Mathematics with LaTeX
KaTeX runs at build time, not on page load: the expressions are already in the HTML, they appear instantly, and screen readers can read them.
Contents
Most Hugo themes render mathematics by shipping KaTeX or MathJax to the browser and having it re-scan the whole page. This theme does not: Hugo calls KaTeX directly during the build and writes HTML with MathML into the static file. The reader downloads exactly one extra stylesheet.
Inline expressions#
Write $...$ or \(...\). The Pythagorean theorem says that, and the golden ratio turns up in places nobody expects. The roots of are.
Display expressions#
Use $$...$$ or \[...\]. Euler’s identity, often called the most beautiful
formula in mathematics:
The Gaussian integral:
The Basel problem, which Euler solved in 1735 at the age of twenty-eight:
Heavier machinery#
Matrices, delimiters that stretch, and multi-line alignment all work:
Conditional probability, written the Bayesian way:
How it works#
Goldmark has a passthrough extension: it recognises the mathematical delimiters and leaves whatever sits between them alone, untouched by the Markdown parser. A render hook then picks up that raw fragment:
{{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") -}}
{{- with try (transform.ToMath .Inner $opts) -}}
{{- with .Err -}}
{{- warnf "blog@tuan: could not render the expression %q" $.Inner -}}
{{- else -}}
{{- $.Page.Store.Set "hasMath" true -}}
{{- .Value -}}
{{- end -}}
{{- end -}}transform.ToMath is KaTeX compiled straight into Hugo. The hasMath flag goes
into Page.Store so that the end of the page only pulls in KaTeX’s stylesheet
when there is actually something to typeset — posts without mathematics download
nothing extra.
Set "output" "mathml" rather than "htmlAndMathml" and the stylesheet goes
away entirely: every current browser renders native MathML. The trade is slightly
coarser spacing than KaTeX’s own HTML output.
Two places to trip#
Because $ opens an expression, writing prices with it can confuse the parser.
Escape it as \$, or wrap it in backticks like $5.
The second one is quieter: never leave a lone = on its own line inside a $$
block. Markdown reads that line as a setext heading and cuts the expression in
half right there. Put = \frac{...} at the start of the next line instead.