Hugo 支持 Mathjax 渲染数学公式

Posted on Mar 26, 2022

用的是 Ataias Pereira Reis 给上游提交的 PR adityatelange/hugo-PaperMod#140 的代码,稍微改了一下开关选项。

layouts/partials/ 目录下创建文件

先创建 math.html

<script type="text/javascript" async
    src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
        MathJax.Hub.Config({
            tex2jax: {
                inlineMath: [['$', '$'], ['\\(', '\\)']],
                displayMath: [['$$', '$$']],
                processEscapes: true,
                processEnvironments: true,
                skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
                TeX: {
                    equationNumbers: { autoNumber: "AMS" },
                    extensions: ["AMSmath.js", "AMSsymbols.js"]
                }
            }
        });
        MathJax.Hub.Queue(function () {
            // Fix <code> tags after MathJax finishes running. This is a
            // hack to overcome a shortcoming of Markdown. Discussion at
            // https://github.com/mojombo/jekyll/issues/199
            var all = MathJax.Hub.getAllJax(), i;
            for (i = 0; i < all.length; i += 1) {
                all[i].SourceElement().parentNode.className += ' has-jax';
            }
        });
        MathJax.Hub.Config({
            // Autonumbering by mathjax
            TeX: { equationNumbers: { autoNumber: "AMS" } }
        });
    </script>

然后创建 head.html 中增加如下的配置:

{{ if or .Params.math .Site.Params.math }}
{{ partial "math.html" . }}
{{ end }}

在 config 或者 page 的 front matter 中配置 math: true,就可以了。

$$y =x$$

$$y =x$$

测试 $y=x$ inline

测试 $y=x$ inline