Enzo Li @ eynzof.com

添加 LaTeX 支持

2019.08.18

为文章加入LaTex语法支持


在模板文件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>

增加后台预览功能


上面修改模板之后,只有在文章发布之后方才看到渲染出来的公式;而在后端自己编辑的时候并不能预览,很是不方便;

在文章 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>

示例


Pω=nω2ω,1+R1v211dx,(xv)xv,P_\omega={n_\omega\over 2}\hbar\omega,{1+R\over 1-v^2}\int\limits_{-1}^{1}dx,(x-v)|x-v|,

x1,2=b±b24ac2a.x_{1,2} = {-b\pm\sqrt{b^2 - 4ac} \over 2a}.

参考资料


https://yq.aliyun.com/articles/16951

https://bell0bytes.eu/syntax-latex/

https://upmath.me/