80dd7b067 theme: Fix border class in render-codeblock template 0d3fde6c9 content: Fix typo 23a4adb29 content: More site => project changes 9243e9f6b content: Rename site configuration to project configuration (phase 2) 330aa2249 content: Miscellaneous edits 25ce893be content: Clarify sort order with PAGE.Rotate b398506dc content: Various dimension improvements c54573d13 content: Use singular form in method section descriptions d9a95fe54 content: Improve description of PAGE.Rotate 154f30600 content: Fix link c71bd2776 content: Address Markdown linting error 72c88e68e content: Improve pages related to content dimensions b85afa645 content: Fix formatting 7aaca8947 content: More site-to-project changes 8e1579030 content: Update quick start guide f7ba1fde2 content: Make new-in into a note 8b9d51584 theme: Address TailwindCSS warnings 3a4c2a25c theme: Address Hugo v0.156.0 deprecations 4f1a2bd7b content: Improve glossary entries 21bcd23a6 content: Update glossary entry c72ef1116 content: Update quick start guide c0737ffab content: Add typography plugin to TailwindCSS example 80bcb868e content: Remove Site.AllPages from examples 2b9ba5831 content: Replace Page.Sites and Site.Sites with hugo.Sites 2cdcc2556 content: Remove outdated badges 5a4beb530 content: Replace Site.Data with hugo.Data de4651b5d content: Update glossary entry 2302825a7 content: Add hugo.Data and note other deprecations bac5da4b5 content: Add hugo.Sites and update the other Sites methods 0f7d99153 content: Add Site.IsDefault f888f33bb content: Update glossary entries 65311c2de content: Include the "build" subcommand where appropriate 4991320d2 content: Standard shell language code in info strings b16d9f162 theme: Style todo lists f121450c6 content: Update version references 5a81dd8c2 content: Update CLI documentation f3ae0ce86 content: Rename site configuration to project configuration (phase 1) 9c8327119 content: Miscellaneous edits fbff91e22 Update HUGO_VERSION to 0.156.0 2ec625ae8 content: Restore snap installation instructions fc8c246b8 content: Clarify module initialization git-subtree-dir: docs git-subtree-split: 80dd7b067c31c28b13c51f3ac4636890509a4bb7
7.2 KiB
title, description, categories, keywords, params, aliases
| title | description | categories | keywords | params | aliases | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| transform.ToMath | Renders mathematical equations and expressions written in the LaTeX markup language. |
|
|
{{< new-in 0.132.0 />}}
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.
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
Note
By default, Hugo renders mathematical markup to MathML, and does not require any CSS to display the result.
To optimize rendering quality and accessibility, use the
htmlAndMathmloutput option as described below. This approach requires an external stylesheet.
{{ $opts := dict "output" "htmlAndMathml" }}
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" $opts }}
Options
Pass a map of options as the second argument to the transform.ToMath function. The options below are a subset of the KaTeX rendering options.
- displayMode
- (
bool) Whether to render in display mode instead of inline mode. Default isfalse. - errorColor
- (
string) The color of the error messages expressed as an RGB hexadecimal color. Default is#cc0000. - fleqn
- (
bool) Whether to render flush left with a 2em left margin. Default isfalse. - macros
- (
map) A map of macros to be used in the math expression. Default is{}.{{ $macros := dict "\\addBar" "\\bar{#1}" "\\bold" "\\mathbf{#1}" }} {{ $opts := dict "macros" $macros }} {{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }} - minRuleThickness
- (
float) The minimum thickness of the fraction lines inem. Default is0.04. - output
- (
string) Determines the markup language of the output, one ofhtml,mathml, orhtmlAndMathml. Default ismathml.With
htmlandhtmlAndMathmlyou must include the KaTeX style sheet within theheadelement of your base template.<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.css" integrity="sha384-WcoG4HRXMzYzfCgiyfrySxx90XSl2rxY5mnVY5TwtWE6KLrArNKn0T/mOgNL0Mmi" crossorigin="anonymous" > - strict
- {{< new-in 0.147.6 />}}
- (
string) Controls how KaTeX handles LaTeX features that offer convenience but aren't officially supported, one oferror,ignore, orwarn. Default iserror.error: Throws an error when convenient, unsupported LaTeX features are encountered.ignore: Allows convenient, unsupported LaTeX features without any feedback.warn: {{< new-in 0.147.7 />}} Emits a warning when convenient, unsupported LaTeX features are encountered.
The
newLineInDisplayModeerror code, which flags the use of\\or\newlinein display mode outside an array or tabular environment, is intentionally designed not to throw an error, despite this behavior being questionable. - throwOnError
- (
bool) Whether to throw aParseErrorwhen KaTeX encounters an unsupported command or invalid LaTeX. Default istrue.
Error handling
There are three ways to handle errors:
- Let KaTeX throw an error and fail the build. This is the default behavior.
- Set the
throwOnErroroption tofalseto make KaTeX render the expression as an error instead of throwing an error. See options. - Handle the error in your template.
The example below demonstrates error handing within a template.
Example
Instead of client-side JavaScript rendering of mathematical markup using MathJax or KaTeX, create a passthrough render hook which calls the transform.ToMath function.
- Step 1
- 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.
{{< code-toggle file=hugo copy=true >}}
[markup.goldmark.extensions.passthrough]
enable = true
[markup.goldmark.extensions.passthrough.delimiters]
block = [['[', ']'], ['$', '$']]
inline = '(', ')'
{{< /code-toggle >}}
Note
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.
- Step 2
- Create a passthrough render hook to capture and render the LaTeX markup.4
{{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }}
{{- with try (transform.ToMath .Inner $opts) }}
{{- with .Err }}
{{- 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 }}
{{- else }}
{{- .Value }}
{{- $.Page.Store.Set "hasMath" true }}
{{- end }}
{{- end -}}
- Step 3
- In your base template, conditionally include the KaTeX CSS within the head element.
<head> {{ $noop := .WordCount }} {{ if .Page.Store.Get "hasMath" }} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.css" integrity="sha384-WcoG4HRXMzYzfCgiyfrySxx90XSl2rxY5mnVY5TwtWE6KLrArNKn0T/mOgNL0Mmi" crossorigin="anonymous" > {{ end }} </head>In the above, note the use of a noop statement to force content rendering before we check the value of
hasMathwith theStore.Getmethod.Note
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 calls the
ContentorSummarymethods while ranging through its page collection, the list page will not load the KaTeX CSS.If this affects your site, use this conditional logic instead:
{{ $noop := .WordCount }} {{ if or (.Page.Store.Get "hasMath") .IsNode }} <link rel="stylesheet" href="..."> {{ end }} - Step 4
- Add some mathematical markup to your content, then test.
This is an inline \(a^*=x-b^*\) equation. These are block equations: \[a^*=x-b^*\] $$a^*=x-b^*$$
Chemistry
{{< new-in 0.144.0 />}}
You can also use the transform.ToMath function to render chemical equations, leveraging the \ce and \pu functions from the mhchem package.
$$C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}$$
C_p[\ce{H2O(l)}] = \pu{75.3 J // mol K}