設定數學式
在 Zensical 中,要做如下的設定才會秀出正確的數學方程式。這會啟用 Arithmatex,並載入 MathJax。
設定
在 docs/js 中加入:
js/mathjax.js
window.MathJax = {
tex: {
inlineMath: [["\\(", "\\)"]],
displayMath: [["\\[", "\\]"]],
processEscapes: true,
processEnvironments: true
},
options: {
ignoreHtmlClass: ".*|",
processHtmlClass: "arithmatex"
}
};
document$.subscribe(() => {
MathJax.startup.output.clearCache()
MathJax.typesetClear()
MathJax.texReset()
MathJax.typesetPromise()
})
component$.subscribe(({ ref }) => {
if (ref.classList.contains("md-annotation"))
MathJax.typesetPromise([ref])
})
並在 zensical.toml 中加入如下設定:
[project.markdown_extensions.pymdownx.arithmatex]
generic = true
[project]
extra_javascript = [
"js/mathjax.js",
"https://unpkg.com/mathjax@3/es5/tex-mml-chtml.js",
]
document$.subscribe 是為了搭配 instant navigation,換頁後數學式仍會重新排版。
測試
如果要獨立顯示數學公式,使用區塊語法 $$...$$ 或 \[...\],方程式通常會另起一行並置中顯示。
這是區塊公式:
\[
\int_0^1 x^2 \,dx = \frac{1}{3}
\]
如果要在文本段落內插入數學公式,使用行內語法 $...$ 或 \(...\),方程式通常不會換行。
這是行內公式 \(E = mc^2\)。
改用 KaTeX
除了 MathJax,也可以改用 KaTeX。它是輕量的函式庫,主打速度與簡潔,支援一部分的 LaTeX 語法,可以輸出成 HTML 與 SVG。
步驟 1:建立 docs/js/katex.js
docs/js/katex.js
document$.subscribe(({ body }) => {
renderMathInElement(body, {
delimiters: [
{ left: "$$", right: "$$", display: true },
{ left: "$", right: "$", display: false },
{ left: "\\(", right: "\\)", display: false },
{ left: "\\[", right: "\\]", display: true }
],
})
})
document$.subscribe 讓 KaTeX 可以搭配 instant navigation。
步驟 2:在 zensical.toml 載入
[project]
extra_javascript = [
"js/katex.js",
"https://unpkg.com/katex@0/dist/katex.min.js",
"https://unpkg.com/katex@0/dist/contrib/auto-render.min.js",
]
extra_css = [
"https://unpkg.com/katex@0/dist/katex.min.css",
]
[project.markdown_extensions.pymdownx.arithmatex]
generic = true
MathJax 與 KaTeX 擇一
兩者不要同時載入。要改用 KaTeX,就要把上面的 MathJax 設定(js/mathjax.js 與 tex-mml-chtml.js)移除。
MathJax 與 KaTeX 怎麼選?
| 考量 | MathJax | KaTeX |
|---|---|---|
| 速度 | 較慢 | 較快,適合大量、複雜的公式 |
| 語法支援 | 較廣,支援更多 LaTeX 指令,也支援 AsciiMath、MathML | 只支援部分 LaTeX |
| 輸出格式 | HTML、SVG,還有 MathML(螢幕閱讀器可讀,對無障礙很重要) | HTML、SVG |
| 設定彈性 | 較高,可精細控制行為 | 較簡單 |
| 瀏覽器相容 | 較廣,包含較舊的瀏覽器 | 現代瀏覽器 |
簡單來說:KaTeX 以速度與簡潔取勝,MathJax 則功能較多、相容性較好,代價是速度較慢。看你的需求與限制決定。本教學網站使用的是 MathJax。