写博文偶尔遇到想要编写公式的场景,默认的Ghost并不会支持Latex,需要自己添加;
网上找了一大堆文章,无非都是使用 MathJax脚本 ,这里总结一下安装步骤
1、让文章支持MathJax
在模板文件 content/themes/casper/default.hbs
中的 <\body>
前 加入以下内容:
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\\\(','\\\\)']],
processEscapes: true
}
});
</script>
2、增加后台预览功能
上面修改模板之后,只有在文章 发布之后 方才看到渲染出来的公式;而在后端自己编辑的时候并不能预览,很是不方便;
在文章 MathJax and Syntax Highlighting (with Live Preview) on Ghost 有讲如何实现预览的方法:
在 ghost/core/server/views/default.hbs
模板问的 <\body>
前 加入以下内容:
{{! Load and configure mathjax }}
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
{{! Re-render MathJax in live preview}}
<script>
jQuery(function(){
var timeout;
function mathjaxify()
{
var preview = document.getElementsByClassName('rendered-markdown')[0];
if (typeof(typeset) == "undefined" || typeset == true) {
MathJax.Hub.Queue(["Typeset", MathJax.Hub, preview]); // renders mathjax if 'typeset' is true (or undefined)
typesetStubbornMath();
}
// Render the bits of math that have inexplicably still failed to render, while
// leaving the rest alone. (If you try to typeset the whole page, it will break
// other things)
function typesetStubbornMath() {
$(".MathJax_Preview").each( function() {
if($(this).text() != "") {
MathJax.Hub.Queue(["Typeset", MathJax.Hub, $(this).attr("id")]);
}
});
}
}
// 每隔200ms检查一次元素
setTimeout(function(){
if($('.entry-markdown').length > 0){
// Listen for Key Presses if on Editor
jQuery(document).keypress(function(event) {
console.log('11');
clearTimeout(timeout);
timeout = setTimeout(mathjaxify, 1000);
});
}else{
setTimeout(arguments.callee,200);
}
},200);
// Check for Change of Post Selection
setTimeout(function(){
console.log('22');
jQuery('.content-list-content li').click(function(){ mathjaxify(); });
}, 500);
});
</script>
和原文相比,我这里稍微修改了下实现,使用轮询去获取
$('.entry-markdown')
对象,否则会报错;
这样就能让你的Ghost支持 Mathjax
了。
3、总结
在《Latex入门》书中有说,单美元符号是$..$
是显示行内公式,比如 E = mc^2
会显示 E=mc2E=mc2 ;
不带编号的显示公式,推荐使用方括号 \[ ... \]
:
E=mc2E=mc2
也有些人会使用双美元符号
$$...$$
,只是后者会产生不良的间距,当然这是在长篇论文中会涉及到这个问题,在博客里面的公式基本遇不到这种情况;
这里需要注意,因为Ghost 使用markdown解析器解析语法 的,所以 使用
\[E = mc^2\]
会解析成[E=mc^2]
,所以要想成功解析出来,需要对反斜杠再转义一次:\\[E = mc^2\\]
;
3.1、todo
- 实现不转义的功能,参考 让Ghost完美支持Latex