hexo博客fluid主题下处理数学公式

fluid主题自带了mathjax渲染器,该渲染器需要适当的配置

修改主题配置

修改_config.fluid.yml:

1
2
3
4
5
6
7
8
9
math:
# 开启后文章默认可用,自定义页面如需使用,需在 Front-matter 中指定 `math: true`
enable: true

# 开启后,只有在文章 Front-matter 里指定 `math: true` 才会在文章页启动公式转换,以便在页面不包含公式时提高加载速度
specific: false

# Options: mathjax | katex
engine: mathjax

启用math并设置引擎为mathjax

hexo 交叉引用

mathjax的数学公式支持自动编号并交叉引用,但是hexo的fluid主题默认没有开交叉引用,需要修改源代码。参考mathjax官方文档:https://docs.mathjax.org/en/latest/input/tex/eqnumbers.html

需要给mathjax添加配置:

1
2
3
4
5
window.MathJax = {
tex: {
tags: 'ams'
}
};

找到node_modules\hexo-theme-fluid\layout\_partials\plugins\math.ejs,将上面的配置选项添加到mathjax的配置中即可。

书写数学公式的方法

markdown有几种数学公式书写方法,但是hexo和博客园的公式不完全兼容,有一些踩坑点,接下来会逐一介绍。

1. 行内公式

直接用$...$包裹即可

2. 行间公式

写法一:

1
2
3
$$
\boldsymbol{R}=x
$$

渲染结果如下: \[ \boldsymbol{R}=x \]

写法二:

1
2
3
\begin{equation}
\boldsymbol{R}=x
\end{equation}

渲染结果如下:

\[\begin{equation} \boldsymbol{R}=x \end{equation}\]

这两种写法在博客园和hexo都没问题,写法二可以加标签,进行交叉引用。

注意:写法二是不符合MathJax标准的,但是MathJax可以处理,关于这点将在后面做出讨论。

交叉引用的写法

使用\label进行交叉引用

举个例子

1
2
3
4
5
6
\begin{equation}
\boldsymbol{R}=x
\label{eq1}
\end{equation}

我们在公式\eqref{eq1}中提到了balabala

渲染结果如下:

\[\begin{equation} \boldsymbol{R}=x \label{eq1} \end{equation}\]

我们在公式\(\eqref{eq1}\)中提到了balabala

这部分虽然在博客园编辑器中无法预览,但是保存后在网页是可以正确渲染的。

数学公式渲染的bug/踩坑点

1. 使用标准写法导致渲染出错

本人之前写公式合并了上述提到的方法一和方法二:

1
2
3
4
5
$$
\begin{equation}
...
\end{equation}
$$

这种写法在博客园是可以完美支持的,也是最标准的写法,但是在hexo中会导致渲染出错。根据MathJax文档描述:

Note that, as opposed to true LaTeX, MathJax processes all environments when wrapped inside math delimiters, even those like \begin{equation}...\end{equation} that are supposed to be used to initiate math mode. By default, MathJax will also render all environments outside of delimiters, e.g., \begin{matrix}...\end{matrix} would be processed even if it is not in math mode delimiters, though you are encouraged to use proper delimiters for these cases to make your files more compatible with actual LaTeX. This functionality can be controlled via the processEnvironments option in the tex configuration options.
注意,不同于LaTex,MathJax处理的所有数学公式都应该显式地包裹在数学分隔符中(如$...$,即使是\begin{equation}...\end{equation}也应该在数学环境中。但是,MathJax默认会处理所有数学环境,即使\begin{equation}...\end{equation}不在$...$中。但是文档建议始终使用正确的分隔符。

虽然MathJax官方的文档是这么建议的,并且博客园也能很好地支持这种正确的写法,但是,在hexo fluid的渲染模式下,会有问题。当$$\begin{equation}...\end{equation}$$中包含空行时,hexo就不能完美地渲染公式,必须保证公式没有空行才可以。

2. 加粗命令

latex中加粗公式有\bold, \boldsymbol, \bm,这几种在博客园中都支持,但是hexo中仅支持\boldsymbol

hexo支持两种加粗,\mathbf和\boldsymbol,mathbf不支持希腊字母加粗,而且加粗后是正体,boldsymbol加粗后是斜体字母,见下:

\mathbf:\(a\rightarrow\mathbf{a}\)\(\alpha\rightarrow\mathbf{\alpha}\)
\boldsymbol: \(a\rightarrow\boldsymbol{a}\)\(\alpha\rightarrow\boldsymbol{\alpha}\)


hexo博客fluid主题下处理数学公式
https://jcdu.top/2025/03/25/hexo博客fluid主题下处理数学公式/
作者
horizon86
发布于
2025年3月25日
许可协议