hexo博客的Next主题实现数学公式渲染

在做密码学研究时,经常会使用数学公式进行一系列推导计算,而hexo博客默认使用 hexo-renderer-marked 引擎渲染网页,该引擎会把一些特殊的 markdown 符号转换为相应的 html 标签,比如在 markdown 语法中,下划线_代表斜体,会被渲染引擎处理为<em>标签。

因为类 Latex 格式书写的数学公式下划线_表示下标,有特殊的含义,如果被强制转换为<em>标签,那么 MathJax 引擎在渲染数学公式的时候就会出错。类似的语义冲突的符号还包括*, {, }, \\等。

解决方法

更换 Hexo 的 markdown 渲染引擎,hexo-renderer-kramed 引擎是在默认的渲染引擎 hexo-renderer-marked 的基础上修改了一些 bug ,两者比较接近,也比较轻量级。如果你是Windows系统,直接使用Git Bash的命令行在Hexo根目录下使用命令:

npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-kramed --save

然后,更换引擎后行间公式可以正确渲染了,但是这样还没有完全解决问题,行内公式的渲染还是有问题,因为 hexo-renderer-kramed 引擎也有语义冲突的问题。接下来到博客根目录下,找到node_modules\kramed\lib\rules\inline.js,做相应的修改:

var inline = {
  // 第2行修改
  escape: /^\\([`*\[\]()#$+\-.!_>])/,
  ...
  // 第20行修改
  em: /^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
};

在 Next 主题中开启 MathJax 开关

找到根目录下的/themes/next/_config.yml文件,按下Ctrl+F,在弹出的搜索框中输入mathjax查找匹配项,然后你找到了这样几行字,把 math 默认的 false 修改为true

# Math Formulas Render Support
math:
  # Default (true) will load mathjax / katex script on demand.
  # That is it only render those page which has `mathjax: true` in Front-matter.
  # If you set it to false, it will load mathjax / katex srcipt EVERY PAGE.
  per_page: true

  # hexo-renderer-pandoc (or hexo-renderer-kramed) required for full MathJax support.
  mathjax:
    enable: true
    # See: https://mhchem.github.io/MathJax-mhchem/
    mhchem: true

在需要使用数学公式的文章的Front-matter里打开mathjax开关,考虑只有在用到公式的页面才加载 Mathjax,这样不需要渲染数学公式的页面的访问速度就不会受到影响了。如下:

---
title: Python实现RSA算法
categories: 密码学
tags: RSA
abbrlink: 49034
mathjax: true
date: 2020-08-02 09:16:24
---

最后一键三连

hexo clean && hexo g && hexo d

即可生效。

posted @ 2020-12-07 10:48  和铃  阅读(689)  评论(0编辑  收藏  举报