<-- Home |--hugo

Katex vs. Mathjax in Hugo中数学公式的显示

在Hugo中的数学公式可以用两种方式显示:Katex和Mathjax。

Katex的速度比Mathjax快,但是Mathjax的公式显示效果比Katex好。

在Hugo中,可以很容易的设置数学公式的显示方式。

mathjax+Hugo的配置中有详细的配置方法。

只需要再建一个mathkatex.html在同样的位置。

 1<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css"
 2    integrity="sha384-zh0CIslj+VczCZtlzBcjt5ppRcsAmDnRem7ESsYwWwg3m/OaJ2l4x7YBZl9Kxxib" crossorigin="anonymous">
 3<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.js"
 4    integrity="sha384-Rma6DA2IPUwhNxmrB/7S3Tno0YY7sFu9WSYMCuulLhIqYSGZ2gKCJWIqhBWqMQfh" crossorigin="anonymous">
 5    </script>
 6<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/contrib/auto-render.min.js"
 7    integrity="sha384-hCXGrW6PitJEwbkoStFjeJxv+fSOOQKOPbJxSfM6G5sWZjAyWhXiTIIAmQqnlLlh" crossorigin="anonymous"
 8    onload="renderMathInElement(document.body);">
 9    </script>
10<script>
11    document.addEventListener("DOMContentLoaded", function () {
12        renderMathInElement(document.body, {
13            delimiters: [
14                { left: '\\[', right: '\\]', display: true },   // block
15                { left: '$$', right: '$$', display: true },     // block
16                { left: '\\(', right: '\\)', display: false },  // inline
17                { left: '$', right: '$', display: false },     // inline
18            ],
19            throwOnError: false
20        });
21    });
22</script>

然后在Hugo页面的head标签中增加:

1  {{ if .Params.mathjax }}
2  {{ partial "mathjax.html" . }}
3  {{ else if or .Params.mathkatex .Site.Params.mathkatex }}
4  {{ partial "mathkatex.html" . }}
5  {{ end }}

这段话的逻辑是:如果在当前页面中设置mathkatex = true,则使用Mathjax,否则如果当前页面中设置mathkatex = true,或者Hugo的配置中设置mathkatex = true,则使用Katex。

当然,我们可以提前在hugo.toml中增加如下参数,对应.Site.Params.mathkatex

1[params]
2  mathkatex = true

然后,除非页面中明确指定mathkatex = true,否则默认使用Katex。


文章标签

|-->hugo |-->katex |-->mathjax


GitHub