Debian Codegraph @

docs/content/en/functions/transform/ToMath.md

raw
1 ---
2 title: transform.ToMath
3 description: Renders mathematical equations and expressions written in the LaTeX markup language.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: template.HTML
10 signatures: ['transform.ToMath INPUT [OPTIONS]']
11 aliases: [/functions/tomath]
12 ---
13
14 Hugo uses an embedded instance of the [KaTeX][] display engine to render mathematical markup to HTML. You do not need to install the KaTeX display engine.
15
16 ```go-html-template
17 {{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
18 ```
19
20 > [!NOTE]
21 > By default, Hugo renders mathematical markup to [MathML][], and does not require any CSS to display the result.
22 >
23 > To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet.
24
25 ```go-html-template
26 {{ $opts := dict "output" "htmlAndMathml" }}
27 {{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" $opts }}
28 ```
29
30 ## Options
31
32 The `transform.ToMath` function accepts an options map. These options are a subset of the KaTeX [rendering options][].
33
34 `displayMode`
35 : (`bool`) Whether to render in display mode instead of inline mode. Default is `false`.
36
37 `errorColor`
38 : (`string`) The color of the error messages expressed as an RGB [hexadecimal color][]. Default is `#cc0000`.
39
40 `fleqn`
41 : (`bool`) Whether to render flush left with a 2em left margin. Default is `false`.
42
43 `macros`
44 : (`map`) A map of macros to be used in the math expression. Default is `{}`.
45
46 ```go-html-template
47 {{ $macros := dict
48 "\\addBar" "\\bar{#1}"
49 "\\bold" "\\mathbf{#1}"
50 }}
51 {{ $opts := dict "macros" $macros }}
52 {{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }}
53 ```
54
55 `minRuleThickness`
56 : (`float`) The minimum thickness of the fraction lines in `em`. Default is `0.04`.
57
58 `output`
59 : (`string`) Determines the markup language of the output, one of `html`, `mathml`, or `htmlAndMathml`. Default is `mathml`.
60
61 With `html` and `htmlAndMathml` you must include the KaTeX style sheet within the `head` element of your _base_ template.
62
63 ```html
64 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-vlBdW0r3AcZO/HboRPznQNowvexd3fY8qHOWkBi5q7KGgqJ+F48+DceybYmrVbmB" crossorigin="anonymous">
65 ```
66
67 `strict`
68 : {{< new-in 0.147.6 />}}
69 : (`string`) Controls how KaTeX handles LaTeX features that offer convenience but aren't officially supported, one of `error`, `ignore`, or `warn`. Default is `error`.
70
71 - `error`: Throws an error when convenient, unsupported LaTeX features are encountered.
72 - `ignore`: Allows convenient, unsupported LaTeX features without any feedback.
73 - `warn`: {{< new-in 0.147.7 />}} Emits a warning when convenient, unsupported LaTeX features are encountered.
74
75 The `newLineInDisplayMode` error code, which flags the use of `\\` or `\newline` in display mode outside an array or tabular environment, is intentionally designed not to throw an error, despite this behavior being questionable.
76
77 `throwOnError`
78 : (`bool`) Whether to throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTeX. Default is `true`.
79
80 Hugo caches the result, so calling the function multiple times with the same arguments incurs no additional overhead.
81
82 ## Error handling
83
84 There are three ways to handle errors:
85
86 1. Let KaTeX throw an error and fail the build. This is the default behavior.
87 1. Set the `throwOnError` option to `false` to make KaTeX render the expression as an error instead of throwing an error. See [options](#options).
88 1. Handle the error in your template.
89
90 The example below demonstrates error handing within a template.
91
92 ## Example
93
94 Instead of client-side JavaScript rendering of mathematical markup using MathJax or KaTeX, create a passthrough render hook which calls the `transform.ToMath` function.
95
96 Step 1
97 : Enable and configure the Goldmark [passthrough extension][] in your project configuration. The passthrough extension preserves raw Markdown within delimited snippets of text, including the delimiters themselves.
98
99 {{< code-toggle file=hugo copy=true >}}
100 [markup.goldmark.extensions.passthrough]
101 enable = true
102 [markup.goldmark.extensions.passthrough.delimiters]
103 block = [['\[', '\]'], ['$$', '$$']]
104 inline = [['\(', '\)']]
105 {{< /code-toggle >}}
106
107 > [!NOTE]
108 > The configuration above precludes the use of the `$...$` delimiter pair for inline equations. Although you can add this delimiter pair to the configuration, you must double-escape the `$` symbol when used outside of math contexts to avoid unintended formatting.
109
110 Step 2
111 : Create a [passthrough render hook][] to capture and render the LaTeX markup.4
112
113 ```go-html-template {file="layouts/_markup/render-passthrough.html" copy=true}
114 {{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }}
115 {{- with try (transform.ToMath .Inner $opts) }}
116 {{- with .Err }}
117 {{- errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }}
118 {{- else }}
119 {{- .Value }}
120 {{- $.Page.Store.Set "hasMath" true }}
121 {{- end }}
122 {{- end -}}
123 ```
124
125 Step 3
126 : In your _base_ template, conditionally include the KaTeX CSS within the head element.
127
128 ```go-html-template {file="layouts/baseof.html" copy=true}
129 <head>
130 {{ $noop := .WordCount }}
131 {{ if .Page.Store.Get "hasMath" }}
132 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-vlBdW0r3AcZO/HboRPznQNowvexd3fY8qHOWkBi5q7KGgqJ+F48+DceybYmrVbmB" crossorigin="anonymous">
133 {{ end }}
134 </head>
135 ```
136
137 In the above, note the use of a [noop](g) statement to force content rendering before we check the value of `hasMath` with the `Store.Get` method.
138
139 > [!NOTE]
140 > This conditional approach only identifies math on the current page. Mathematical expressions will not display correctly when one page's content is embedded within another. For example, if a [list page](g) calls the [`Content`][] or [`Summary`][] methods while ranging through its page collection, the list page will not load the KaTeX CSS.
141 >
142 > If this affects your site, use this conditional logic instead:
143 >
144 > ```go-html-template {file="layouts/baseof.html" copy=true}
145 > {{ $noop := .WordCount }}
146 > {{ if or (.Page.Store.Get "hasMath") .IsNode }}
147 > <link rel="stylesheet" href="...">
148 > {{ end }}
149 > ```
150
151 Step 4
152 : Add some mathematical markup to your content, then test.
153
154 ```md {file="content/example.md"}
155 This is an inline \(a^*=x-b^*\) equation.
156
157 These are block equations:
158
159 \[a^*=x-b^*\]
160
161 $$a^*=x-b^*$$
162 ```
163
164 ## Chemistry
165
166 {{< new-in 0.144.0 />}}
167
168 You can also use the `transform.ToMath` function to render chemical equations, leveraging the `\ce` and `\pu` functions from the [`mhchem`][] package.
169
170 ```md
171 $$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
172 ```
173
174 $$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
175
176 [KaTeX]: https://katex.org/
177 [MathML]: https://developer.mozilla.org/en-US/docs/Web/MathML
178 [`Content`]: /methods/page/content/
179 [`Summary`]: /methods/page/summary/
180 [`mhchem`]: https://mhchem.github.io/MathJax-mhchem/
181 [hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
182 [passthrough extension]: /configuration/markup/#passthrough
183 [passthrough render hook]: /render-hooks/passthrough/
184 [rendering options]: https://katex.org/docs/options.html