Hugo的数学公式支持

较早之前使用了 mmark 格式让 Hugo 支持数学公式,但是问题比较多,不能满足我的需求。最近对此做了一些修正,借鉴其他人的成果,修改了我的 noteworthy 主题,通过 MathJax 实现了对数学公式的支持。

具体的实现步骤如下。

加入 MathJax 渲染代码

在主题目录的部件模板目录 [noteworthy]/layouts/partials/ 下新建一个 mathjax.html 文件用来集中存放渲染代码。在 mathjax.html 中加入以下内容。

{{ if .Params.math }}
<script>
  MathJax = {
    tex: {
      inlineMath: [["$", "$"]],
    },
    displayMath: [
      ["$$", "$$"],
      ["\[\[", "\]\]"],
    ],
    svg: {
      fontCache: "global",
    },
  };
</script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script
  id="MathJax-script"
  async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"
></script>
{{ end }}

引用 mathjax.html 文件

在生成页面时必须引用的其他任一部件模板中引用上述 mathjax.html,从而使得在生成的页面中间接引用mathjax.html实现链接 MathJax 渲染。可以在 [noteworthy]/layouts/partials/head.html中加入 [noteworthy]/layouts/partials/

<head> 
    <!-- 原始内容 -->

    {{ partial "mathjax.html" . }}
</head>

修改默认创建模板

可以在创建 md 文件时在文件头部的字段中显式指明 math 字段实现数学公式支持,为了避免每次写博客时都重新指明上述字段,直接在默认的创建模板 [BlogRoot]/archetypes/default.md 中加入该字段。顺便也加入一个 <!--more--> 用来指明截断文章摘要的位置。

---
title: " "
date: {{ .Date }}
description: " "
tags: [, ]
draft: true
math: true
---

 <!--more-->

测试示例

可以使用 $行内公式$书写行内公式,可以使用 $$行间公式$$书写行间公式。行内公式示例$ 2 * \sqrt{b^2+4ac} $显示为$ 2 * \sqrt{b^2+4ac} $

为了避免出现一些特殊字符与字符序列的转义问题,行间公式则推荐用<div></div>来包含。如

<div>
$$
\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
$$
</div>

显示为

$$ \begin{matrix} 1 & x & x^2 \\ 1 & y & y^2 \\ 1 & z & z^2 \\ \end{matrix} $$

参考链接

在Hugo中使用MathJax

Hugo 问题汇总

Hugo添加MathJax数学公式支持