mathjax in hexo

最近将博客从octopress迁移到了hexo。 如果使用hexo默认的markdown解析器,然后在用mathjax进行公式显示,存在字符转义的问题。

默认的markdown解析器会将latex中的下划线和’'进行转义。公式不能正常显示,只有手动转义。

然后在网上找到一篇文章: Play MathJax with hexo-renderer-pandoc

介绍使用pandochexo-renderer-pandoc

步骤

  1. Firstly, make sure you have installed pandoc.
  2. Secondly, cd into your hexo root folder and execute the following command:
1
$ npm install hexo-renderer-pandoc --save
  1. Create a file named mathjax.ejs in the folder like theme_folder/layout/_partial/, the code in mathjax.ejs are as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>


<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
}
});
</script>


<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for(i=0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>


<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

The gist is here: mathjax.ejs gist

  1. Add the snippits below in theme_folder/layout/_partial/after_footer.ejs

    1
    2
    3
    <% if (page.mathjax){ %>
    <%- partial('mathjax') %>
    <% } %>

  2. Add mathjax: false for _config.yml in the root directory of your Hexo init folder. It is some thing like this:

    1
    mathjax: false

  3. For the post you want to load MathJax, add mathjax: true at the front-matter (文章开始的头部). By this method you can avoid unnecessary latency for loading Mathjax scripts. Just some thing as follows:

    1
    mathjax: true

  4. Delete the public folder and excute hexo generate again to make the modified Hexo theme work.

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
The **characteristic polynomial** $\chi(\lambda)$ of the $3 \times 3$ matrix
$$
\left( \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i
\end{array} \right)
$$
is given by the formula
$$
\chi(\lambda) = \left| \begin{array}{ccc}
\lambda - a & -b & -c \\
-d & \lambda - e & -f \\
-g & -h & \lambda - i
\end{array} \right|.
$$

The characteristic polynomial \(\chi(\lambda)\) of the \(3 \times 3\) matrix

\[ \left( \begin{array}{ccc} a & b & c \\ d & e & f \\ g & h & i \end{array} \right) \]

is given by the formula

\[ \chi(\lambda) = \left| \begin{array}{ccc} \lambda - a & -b & -c \\ -d & \lambda - e & -f \\ -g & -h & \lambda - i \end{array} \right|. \]