如何在Hexo中使用Mathjax渲染LaTeX数学公式

平时使用markdown写文档的时候,免不了会碰到数学公式,好在有强大的Mathjax,可以解析数学公式。

基于Hexo搭建的个人博客,默认情况下渲染数学公式会出现各种各样的问题。

Hexo默认使用"hexo-renderer-marked"引擎渲染markdown,该引擎会把一些特殊的markdown符号转换为相应的html标签。

解决方案

解决方案有很多,可以网上搜下,为了节省大家的时间,这里提供亲身测试过的方法。

更换Hexo的markdown渲染引擎,用hexo-renderer-markdown-it-plus引擎替换默认的渲染引擎hexo-renderer-marked即可。

安装

先卸载hexo-renderer-marked,再安装hexo-renderer-markdown-it-plus插件

npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-markdown-it-plus --save

配置

安装插件后,如果未正常渲染LaTeX数学公式,在博客配置文件_config.yml中添加

markdown_it_plus:
highlight: true
html: true
xhtmlOut: true
breaks: true
langPrefix:
linkify: true
typographer:
quotes: “”‘’
plugins:
- plugin:
name: markdown-it-katex
enable: true
- plugin:
name: markdown-it-mark
enable: false

文章启用mathjax

title: Hello World
mathjax: true

加载CSS

最后在网页head部分加载mathjax样式表就搞定了

<link href="https://cdn.bootcss.com/KaTeX/0.7.1/katex.min.css" rel="stylesheet">

举个栗子

$$
H=-\sum_{i=1}^N (\sigma_{i}^x \sigma_{i+1}^x+g \sigma_{i}^z)
$$

$$
f(n) = \begin{cases}
\frac{n}{2},
& \text{if } n\text{ is even}
\\ 3n+1, & \text{if } n\text{ is odd}
\end{cases}
$$

上面的代码渲染后显示如下:

H=i=1N(σixσi+1x+gσiz)H=-\sum_{i=1}^N (\sigma_{i}^x \sigma_{i+1}^x+g \sigma_{i}^z)

f(n)={n2,ifnis even3n+1,ifnis oddf(n) = \begin{cases} \frac{n}{2}, & \text{if } n\text{ is even} \\ 3n+1, & \text{if } n\text{ is odd} \end{cases}