Debian Codegraph @

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

raw
1 ---
2 title: transform.ToMath
3 description: Returns the given mathematical markup, written in the LaTeX language, rendered to HTML.
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 Hugo caches the result to disk in the [`misc`][] file cache, so calling the function multiple times with the same arguments incurs no additional overhead.
21
22 > [!NOTE]
23 > By default, Hugo renders mathematical markup to [MathML][], and does not require any CSS to display the result.
24 >
25 > To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet.
26
27 ```go-html-template
28 {{ $opts := dict "output" "htmlAndMathml" }}
29 {{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" $opts }}
30 ```
31
32 ## Options
33
34 The `transform.ToMath` function accepts an options map. These options are a subset of the KaTeX [rendering options][].
35
36 `displayMode`
37 : (`bool`) Whether to render in display mode instead of inline mode. Default is `false`.
38
39 `errorColor`
40 : (`string`) The color of the error messages expressed as an RGB [hexadecimal color][]. Default is `#cc0000`.
41
42 `fleqn`
43 : (`bool`) Whether to render flush left with a 2em left margin. Default is `false`.
44
45 `macros`
46 : (`map`) A map of macros to be used in the math expression. Default is `{}`.
47
48 ```go-html-template
49 {{ $macros := dict
50 "\\addBar" "\\bar{#1}"
51 "\\bold" "\\mathbf{#1}"
52 }}
53 {{ $opts := dict "macros" $macros }}
54 {{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }}
55 ```
56
57 `minRuleThickness`
58 : (`float`) The minimum thickness of the fraction lines in `em`. Default is `0.04`.
59
60 `output`
61 : (`string`) Determines the markup language of the output, one of `html`, `mathml`, or `htmlAndMathml`. Default is `mathml`.
62
63 With `html` and `htmlAndMathml` you must include the KaTeX style sheet within the `head` element of your _base_ template.
64
65 ```html
66 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-u1zONI5gPXUx0UKI62c75/zww972y0v2rSK5ZYlVdS6xEuWDeZWUI66v6t1gvlXJ" crossorigin="anonymous">
67 ```
68
69 `strict`
70 : {{< new-in 0.147.6 />}}
71 : (`string`) Controls how KaTeX handles LaTeX features that offer convenience but aren't officially supported, one of `error`, `ignore`, or `warn`. Default is `error`.
72
73 - `error`: Throws an error when convenient, unsupported LaTeX features are encountered.
74 - `ignore`: Allows convenient, unsupported LaTeX features without any feedback.
75 - `warn`: {{< new-in 0.147.7 />}} Emits a warning when convenient, unsupported LaTeX features are encountered.
76
77 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.
78
79 `throwOnError`
80 : (`bool`) Whether to throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTeX. Default is `true`.
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-u1zONI5gPXUx0UKI62c75/zww972y0v2rSK5ZYlVdS6xEuWDeZWUI66v6t1gvlXJ" 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 [`misc`]: /configuration/caches/#misc
182 [hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
183 [passthrough extension]: /configuration/markup/#passthrough
184 [passthrough render hook]: /render-hooks/passthrough/
185 [rendering options]: https://katex.org/docs/options.html