要在 Hugo 中使用 Latex 語法撰寫數學式,需讓寫在 Markdown 中的 Latex 語法被 MathJaxKatex 能讀取並轉換為數學表示式。

如以下 Latex 語法

x = {-b \pm \sqrt{b^2-4ac} \over 2a}

轉換成對應的數學表示為

$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$

過去要在 Hugo 達成該效果須使用 Shortcodes 等方式來達成,而在 v0.122.0 版本後可透過 goldmark (Hugo 預設的 Markdown parser) 提供的 passthrough extension 設定來達成。以下為使用 MathJax 為 Markdown 數學示 Render 的設定方式

設定 Hugo 參數檔

在 hugo.toml 設定檔中加入以下設定內容

[markup]
  [markup.goldmark]
    [markup.goldmark.extensions]
      [markup.goldmark.extensions.passthrough]
        enable = true
        [markup.goldmark.extensions.passthrough.delimiters]
          block = [['\[', '\]'], ['$$', '$$']]
          inline = [['\(', '\)'], ['$', '$']]
[params]
  math = true

其中 block 的設定代表 goldmark 不會將 Markdown 中 (\[,\]) 與 ($$, $$) 所包含的區間轉換成 HTML 標籤而是直接放入 HTML 文件中。inline 設定同理,只是 block 中的數學式會獨立為一個區塊而 inline 內的 Latex 數學示則是會包含在同一個段落中。

此外 Latex 文章中常使用 ('$', '$') 在段落中顯示數學示範圍,但因有時會使用 $ 符號來代表貨幣單位,因此如果使用的 ('$', '$') 來標記 Latex 數學式則建議使用 \\$ 符號來標注貨幣單位避免產生範圍檢查問題,且建議使用 MathJax 而非 Katex 套件來避免特定問題

此方式預設為使用 toml 格式的 config file。而使用其他格式(.yaml/.json)的設定方式可參考 Hugo 官網文件。此外舊版設定檔名稱為 config.toml,但該名稱可能造成混淆因此在 v0.109.0 後修改為 hugo.toml。

加入 Math script template

在 Hugo project 中建立位於 layouts/partials/math.html 檔案並加入以下 MathJax 內容

<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
<script>
  MathJax = {
    tex: {
      displayMath: [['\\[', '\\]'], ['$$', '$$']],  // block
      inlineMath: [['\\(', '\\)'], ['$', '$']]                  // inline
    }
  };
</script>

之後在網頁 template 中嵌入該樣板內容

<head>
  ...
  {{ if .Param "math" }}
    {{ partialCached "math.html" . }}
  {{ end }}
  ...
</head>

之後只要在網頁中內的分隔符號中加入的 Latex 數學式即可顯示 Render 後結果

$$
e^{i\pi}+1=0
$$

顯示結果為

$$ e^{i\pi}+1=0 $$

而 inline 格式

Euler's formula is $e^{i\pi}+1=0$

顯示結果為

Euler’s formula is $e^{i\pi}+1=0$

若使用的 hugo theme 其中已有相關設定則需主動修改該 theme 內容

設定是否支援 Latex 數學式

之前在 hugo.toml 設定中預設所有網頁都開啟 MathJax 支援,但也可在 markdown 的 front matter 中設定是否開啟支援

---
title: "Show latex math equation in hugo"
author: "peter.li"
date: "2023-12-12T16:00:00+08:00"
math: true
---

其中的 math 設定為 true 時為開啟,false 則為關閉。此外如果不想預設全部頁面都使用 MathJax 可在 hugo.toml 中設定預設的選項為 false 或是不加以設定即可。

[params]
  math = false

Reference