Skip to content

Commit

Permalink
Add error handling to transform.ToMath examples
Browse files Browse the repository at this point in the history
  • Loading branch information
jmooring committed Nov 1, 2024
1 parent 09b1149 commit af73fd9
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 63 deletions.
19 changes: 9 additions & 10 deletions content/en/content-management/mathematics.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
---
title: Mathematics in Markdown
linkTitle: Mathematics
description: Include mathematical equations and expressions in your Markdown using LaTeX or TeX typesetting syntax.
description: Include mathematical equations and expressions in Markdown using the LaTeX markup language.
categories: [content management]
keywords: [chemical,chemistry,latex,math,mathjax,tex,typesetting]
keywords: [katex,latex,math,mathjax,typesetting]
menu:
docs:
parent: content-management
Expand All @@ -24,7 +24,7 @@ JS(\hat{y} || y) &= \frac{1}{2}(KL(y||\frac{y+\hat{y}}{2}) + KL(\hat{y}||\frac{y

## Overview

Mathematical equations and expressions authored in [LaTeX] or [TeX] are common in academic and scientific publications. Your browser typically renders this mathematical markup using an open-source JavaScript display engine such as [MathJax] or [KaTeX].
Mathematical equations and expressions written in [LaTeX] are common in academic and scientific publications. Your browser typically renders this mathematical markup using an open-source JavaScript display engine such as [MathJax] or [KaTeX].

For example, this is the mathematical markup for the equations displayed at the top of this page:

Expand All @@ -45,7 +45,7 @@ The approach described below avoids reliance on platform-specific features like

## Setup

Follow these instructions to include mathematical equations and expressions in your Markdown using LaTeX or TeX typesetting syntax.
Follow these instructions to include mathematical equations and expressions in your Markdown using the LaTeX markup language.

###### Step 1

Expand Down Expand Up @@ -122,7 +122,7 @@ The example above loads the partial template if you have set the `math` paramete

###### Step 4

Include mathematical equations and expressions in your Markdown using LaTeX or TeX typesetting syntax.
Include mathematical equations and expressions in Markdown using the LaTeX markup language.

{{< code file=content/math-examples.md copy=true >}}
This is an inline \(a^*=x-b^*\) equation.
Expand Down Expand Up @@ -173,7 +173,7 @@ If you use the `$...$` delimiter pair for inline equations, and occasionally use

## Engines

MathJax and KaTeX are open-source JavaScript display engines. Both engines are fast, but at the time of this writing MathJax v3.2.2 is slightly faster than KaTeX v0.16.9.
MathJax and KaTeX are open-source JavaScript display engines. Both engines are fast, but at the time of this writing MathJax v3.2.2 is slightly faster than KaTeX v0.16.11.

{{% note %}}
If you use the `$...$` delimiter pair for inline equations, and occasionally use the&nbsp;`$`&nbsp;symbol outside of math contexts, you must use MathJax instead of KaTeX to avoid unintended formatting caused by [this KaTeX limitation](https://github.com/KaTeX/KaTeX/issues/437).
Expand All @@ -184,9 +184,9 @@ See the [inline delimiters](#inline-delimiters) section for details.
To use KaTeX instead of MathJax, replace the partial template from [Step 2] with this:

{{< code file=layouts/partials/math.html copy=true >}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected].9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/[email protected].9/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected].9/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected].11/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/[email protected].11/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected].11/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
renderMathInElement(document.body, {
Expand Down Expand Up @@ -223,6 +223,5 @@ As shown in [Step 2] above, MathJax supports chemical equations without addition
[Step 1]: #step-1
[Step 2]: #step-2
[Step 3]: #step-3
[TeX]: https://en.wikipedia.org/wiki/TeX
[Typora]: https://typora.io/
[passthrough extension]: https://github.com/gohugoio/hugo-goldmark-extensions
111 changes: 65 additions & 46 deletions content/en/functions/transform/ToMath.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,52 @@
---
title: transform.ToMath
description: Renders a math expression using KaTeX.
description: Renders mathematical equations and expressions written in the LaTeX markup language.
categories: []
keywords: [math,katex]
keywords: [katex,latex,math,typesetting]
action:
aliases: []
related:
- content-management/mathematics
returnType: types.Result[template.HTML]
signatures: ['transform.ToMath EXPRESSION [OPTIONS]']
signatures: ['transform.ToMath INPUT [OPTIONS]']
aliases: [/functions/tomath]
toc: true
---

{{< new-in "0.132.0" >}}

{{% note %}}
This feature was introduced in Hugo 0.132.0 and is marked as experimental.
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.

This does not mean that it's going to be removed, but this is our first use of WASI/Wasm in Hugo, and we need to see how it [works in the wild](https://github.com/gohugoio/hugo/issues/12736) before we can set it in stone.
{{% /note %}}
```go-html-template
{{ 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.

## Arguments
To optimize rendering quality and accessibility, use the `htmlAndMathml` output option as described below. This approach requires an external stylesheet.

EXPRESSION
: The math expression to render using KaTeX.
[MathML]: https://developer.mozilla.org/en-US/docs/Web/MathML
{{% /note %}}

OPTIONS
: A map of zero or more options.
```go-html-template
{{ $opts := dict "output" "htmlAndMathml" }}
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" $opts }}
```

## Options

These are a subset of the [KaTeX options].
Pass a map of arguments as the second argument to the `transform.ToMath` function. The options below are a subset of the KaTeX [rendering options].

output
: (`string`). Determines the markup language of the output. One of `html`, `mathml`, or `htmlAndMathml`. Default is `mathml`.

<!-- Indent to prevent spliting the description list. -->

With `html` and `htmlAndMathml` you must include KaTeX CSS within the `head` element of your base template. For example:
With `html` and `htmlAndMathml` you must include the KaTeX style sheet within the `head` element of your base template.

```html
<head>
...
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
...
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
```

displayMode
Expand All @@ -63,50 +64,68 @@ minRuleThickness
macros
: (`map`) A map of macros to be used in the math expression. Default is `{}`.

<!-- Indent to prevent spliting the description list. -->

```go-html-template
{{ $macros := dict
"\\addBar" "\\bar{#1}"
"\\bold" "\\mathbf{#1}"
}}
{{ $opts := dict "macros" $macros }}
{{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }}
```

throwOnError
: (`bool`) If `true` throw a `ParseError` when KaTeX encounters an unsupported command or invalid LaTex. See [error handling]. Default is `true`.

errorColor
: (`string`) The color of the error messages expressed as an RGB [hexadecimal color]. Default is `#cc0000`.

## Examples
## Error handling

### Basic
There are three ways to handle errors:

```go-html-template
{{ transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
```

### Macros
1. Let KaTeX throw an error and fail the build. This is the default behavior.
1. Set the `throwOnError` option to `false` to make KaTeX render the expression as an error instead of throwing an error. See [options].
1. Handle the error in your template as shown below:

```go-html-template
{{ $macros := dict
"\\addBar" "\\bar{#1}"
"\\bold" "\\mathbf{#1}"
}}
{{ $opts := dict "macros" $macros }}
{{ transform.ToMath "\\addBar{y} + \\bold{H}" $opts }}
{{ with transform.ToMath "c = \\pm\\sqrt{a^2 + b^2}" }}
{{ with .Err }}
{{ errorf "Unable to render mathematical markup to HTML using the transform.ToMath template function. The KaTeX display engine threw the following error: %s." . }}
{{ else }}
{{ . }}
{{ end }}
{{ end }}
```

## Error handling
## TBD

There are 3 ways to handle errors from KaTeX:
// TODO

1. Let KaTeX throw an error and make the build fail. This is the default behavior.
1. Handle the error in your template. See the render hook example below.
1. Set the `throwOnError` option to `false` to make KaTeX render the expression as an error instead of throwing an error. See [options](#options).
{{< code file=layouts/_default/_markup/render-passthrough.html copy=true >}}
{{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq .Type "block") }}
{{- with transform.ToMath .Inner $opts }}
{{- with .Err }}
{{ errorf "Unable to render mathematical markup to HTML using the transform.ToMath template function. The KaTeX display engine threw the following error: %s. See %s." . $.Position }}
{{- else }}
{{- . }}
{{- end }}
{{- end }}
{{- .Page.Store.Set "hasMath" true -}}
{{< /code >}}

{{< code file=layouts/_default/_markup/render-passthrough-inline.html copy=true >}}
{{ with transform.ToMath .Inner }}
{{ with .Err }}
{{ errorf "Failed to render KaTeX: %q. See %s" . $.Position }}
{{ else }}
{{ . }}
{{ end }}
Then, in your base template, conditionally include the KaTeX CSS within the head element:

{{< code file=layouts/_default/baseof.html copy=true >}}
{{ $noop := .WordCount }}
{{ if .Store.Get "hasMath" }}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
{{ end }}
{{- /* chomp trailing newline */ -}}
{{< /code >}}

[error handling]: #error-handling
[KaTeX options]: https://katex.org/docs/options.html
[hexadecimal color]: https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
[katex]: https://katex.org/
[rendering options]: https://katex.org/docs/options.html
[options]: #options
16 changes: 9 additions & 7 deletions content/en/render-hooks/passthrough.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,19 @@ Hugo populates the `Attributes` map for _block_ passthrough elements. Markdown a

## Example

As an alternative to rendering mathematical expressions with the MathJax or KaTeX display engine, create a passthrough render hook which calls the [`transform.ToMath`] function:
As an alternative to rendering mathematical markup on the client side using the MathJax or KaTeX display engine, create a passthrough render hook which calls the [`transform.ToMath`] function:

[`transform.ToMath`]: /functions/transform/tomath/

{{< code file=layouts/_default/_markup/render-passthrough.html copy=true >}}
{{ if eq .Type "block" }}
{{ $opts := dict "displayMode" true }}
{{ transform.ToMath .Inner $opts }}
{{ else }}
{{ transform.ToMath .Inner }}
{{ end }}
{{- $opts := dict "displayMode" (eq .Type "block") }}
{{- with transform.ToMath .Inner $opts }}
{{- with .Err }}
{{ errorf "Unable to render mathematical markup to HTML using the transform.ToMath template function. The KaTeX display engine threw the following error: %s. See %s." . $.Position }}
{{- else }}
{{- . }}
{{- end }}
{{- end -}}
{{< /code >}}

Although you can use one template with conditional logic as shown above, you can also create separate templates for each [`Type`](#type) of passthrough element:
Expand Down

0 comments on commit af73fd9

Please sign in to comment.