hexo增加math的显示

hexo需要增加对数学公式的显示,目前流行的是使用mathjex.js库在浏览器端实时渲染,使用时只要在head里引用js的地址即可。 但是我不想在没有math的post里引用这个js库,只要在需要是在文章的metadata里标注一下即可。 按照这个思路修改:

1. 设定post的metadata

为post的metadata添加一种属性叫plugins,用以标注这篇文章要用到的渲染特性。 比如这篇文章的metadata是:

1
2
3
4
5
title: hexo增加math的显示
date: 2013-12-31 22:52:37
plugins: [math]
categories: hexo
---

这样如果以后还需要什么特性,直接添加到plugins列表里就可以。

2. 修改theme,添加mathjex.ejs,修改head.ejs

首先在theme中添加mathjex.ejs,便于在head中引用:

1
2
3
4
5
6
7
8
9
10
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(
    {
      tex2jax: {inlineMath: [['$','$']]},
      TeX: {equationNumbers: {autoNumber: ["AMS"], useLabelIds: true}},
    }
  );
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

然后修改head.ejs,在</head>前添加以下代码,在针对plugins的不同特性加载js,当前只有mathjex.js

1
2
3
4
5
6
7
8
9
10
11
  <!-- for plugins in post -->
  <% if (page.plugins && page.plugins.length){
     page.plugins.forEach(function(plugin){ %>

    <% if (plugin == "math") { %>
      <!-- for math display in post -->
      <%- partial('mathjax')%>    
    <% } %>

    
  <% });} %>

3. 增加新的模板math.md,自动添加属性plugins: [math]

scaffolds/下增加一种文章模板math.md,便于用hexo n math [TITLE_NAME]命令直接创建。

1
2
3
4
5
title: 
date: 
plugins: [math]
categories: 
---

下面显示公式试试:

$ f(x) = \frac{1}{(\sqrt{2\pi} \sigma)} e^{-(x-\mu)^2/2\sigma}$

还有几个问题:

  1. 可以把mathjex的js静态文件嵌入到theme中,因为有时在防火墙内访问不了第三方网站去下载mathjex.js库。 这需要到MathJax官网上把整个项目下载下来,最新的v2.3竟然有33MB,如果不进行精简直接放在静态文件目录里的话, hexo生成html时基本卡死。这等如果有需求时再搞。

  2. mathdown的下划线表示斜体,与math中的下划线冲突。