Skip to content
Go back

Hugoで数式を扱う

  • hugo.tomlに以下を追加して、Passthrough render hooksを有効にする
    • blockinlineで指定される区切り文字に囲まれた部分がrender-passthrough.htmlでレンダリングされる
[markup.goldmark.extensions.passthrough]
enable = true
[markup.goldmark.extensions.passthrough.delimiters]
block = [['$$', '$$']]
inline = [['$', '$']]
  • layouts/_markup/render-passthrough.htmlを以下の内容で作る
    • transform.ToMathが数式をKaTexでレンダリングするように変換してくれる
{{- $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 -}}
  • PaperModテーマの場合、layouts/partials/extend_head.htmlを以下の内容で作る
    • noopは”Store.GetメソッドでhasMathの値を確認する前にコンテンツのレンダリングを強制する”ために必要らしい
{{ $noop := .WordCount }}
{{ if .Page.Store.Get "hasMath" }}
    <link href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css" rel="stylesheet">
{{ end }}

すると、数式を書くとそれ用のフォントで表示されるようになる。

$$
f(x) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp{\left( -\frac{(x - \mu)^2}{2 \sigma^2} \right)}
$$

のように書くと

f(x)=12πσ2exp((xμ)22σ2)f(x) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp{\left( -\frac{(x - \mu)^2}{2 \sigma^2} \right)}

のように表示される。

  • LaTeX\LaTeXには\(\)\[\]を使う記法もあるが、Obsidianは対応していないみたい
  • 今回の場合、$が区切り文字になるので、通常の文字として使いたいときは\$と書く必要がある
  • KaTeXのauto-renderを使う方法も公式サイトで紹介されているが、欠点がいくつかあるので、passthrough render hooksを使う方法のほうが良い
    • 区切り文字を通常の文字として使えなくなる
    • サイト全体でKaTeXを有効化する、または、KaTeXが必要かどうかをページごとに明示する、のいずれかが必要になる
    • passthrough方式なら、数式があるページのみに自動でKaTeXを有効化してくれるので、とても便利

参考文献#