Skip to main content
  1. Maoli's Digital Garden/

Testing Math Rendering

·435 words·3 mins

A Useful Equation #

$$ \|\lambda x+(1-\lambda)y\|^{2}=\lambda\|x\|^{2} + (1-\lambda)\|y\|^{2}-\lambda(1-\lambda)\|x-y\|^{2} $$ Proof: $$ \begin{aligned} \|\lambda x + (1-\lambda) y\|^{2} & = \langle \lambda x + (1-\lambda) y, \lambda x + (1-\lambda) y \rangle \\ & = \lambda^2 \langle x, x \rangle + (1-\lambda)^{2} \langle y, y \rangle + 2\lambda(1-\lambda) \langle x, y \rangle\\ &\overset{(a)} = \lambda^2 \|x\|^2 + (1-\lambda)^2 \|y\|^2 + \lambda(1-\lambda) (\|x\|^2 + \|y\|^2 - \|x-y\|^2) \\ & = \lambda\|x\|^{2} + (1-\lambda)\|y\|^{2}-\lambda(1-\lambda)\|x-y\|^{2} \end{aligned} $$

where $(a)$ is because of ${\langle x, y \rangle = \frac{1}{2} (\|x\|^2 + \|y\|^2 - \|x-y\|^2)}$.

Note #

Problem #

In Hugo congo theme, we use KaTeX to render math equations.

The problem is that Hugo uses Markdown to parse the content, and Markdown uses some characters that are also used by KaTeX. For example, the underscore character (_) is interpreted by Markdown as a way to wrap text in emph blocks (Example by _Example_); while Katex interprets the underscore as a way to create a subscript.

Solution #

To solve this problem, we use the shortcode feature of Hugo. In this case, we use the shortcode to wrap the math equations in HTML code, so that the Markdown parser will not interpret the characters in the math equations.

I modified the shortcode katex.html in the original congo theme as followes:

{{ .Inner }}

which means that the shortcode will just wrap the content in the shortcode with HTML code.

To allow Katex render inline math equations enclosed within $...$ not only \(...\), I modified the vendor.htmlunder the directory layouts/partials in the original congo theme. Now the last part of the file is as follows:

<!-- {{/* Katex */}} -->
{{ if .Page.HasShortcode "katex" }}
    href="[email protected]/dist/katex.min.css"
    src="[email protected]/dist/katex.min.js"
    src="[email protected]/dist/contrib/auto-render.min.js"
    document.addEventListener("DOMContentLoaded", function () {
        renderMathInElement(document.body, {
            delimiters: [
                { left: "$$", right: "$$", display: true },
                { left: "$", right: "$", display: false },
                { left: "\\(", right: "\\)", display: false },
                { left: "\\[", right: "\\]", display: true },
{{ end }}

To insert an inline math equation, use $...$ or \(...\); to insert a display math equation, use $$...$$ or \[...\].

Example #

Display math equation:

A useful equation:
{{< katex >}}

\|\lambda x+(1-\lambda)y\|^{2}=\lambda\|x\|^{2} + (1-\lambda)\|y\|^{2}-\lambda(1-\lambda)\|x-y\|^{2}

{{< /katex >}}

Inline math equation:

{{< katex >}} $\langle x, y \rangle$ {{< /katex >}}

These solutions currently work well for me. 😄

If you find any formatting problems or have any better solutions, please let me know. Thanks!

Reference #