math: enable:true engine:mathjax mathjax: # Use 2.7.1 as default, jsdelivr as default CDN, works everywhere even in China # cdn: //cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML # For newMathJax CDN (cdnjs.cloudflare.com) with fallback to oldMathJax (cdn.mathjax.org). #cdn: //cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML # For direct link to MathJax.js with CloudFlare CDN (cdnjs.cloudflare.com). # cdn: //cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML # For automatic detect latest version link to MathJax.js and get from Bootcss. cdn://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML
{% if theme.math.enable %} {% set is_index_has_math = false %}
{# At home, check if there has `mathjax: true` post #} {% if is_home() %} {% for post in page.posts %} {% if post.mathjax and not is_index_has_math %} {% set is_index_has_math = true %} {% endif %} {% endfor %} {% endif %}
{% if not theme.math.per_page or (is_index_has_math or page.mathjax) %} {% if theme.math.engine == 'mathjax' %} {% include 'mathjax.swig' %} {% elif theme.math.engine == 'katex' %} {% include 'katex.swig' %} {% endif %} {% endif %} {% endif %}
然后调用上面这个的 post.swig 长这样
1 2 3 4 5 6 7 8
{% extends 'includes/layout.swig' %}
{% block body %} {% include 'math/index.swig' %} <article id="post"> <h1>{{ page.title || __('without_title') }}</h1> <p class="page-title-sub"> ......
没错, include 的位置很关键,既不能太前面,也不能太后面。它会按顺序生成 html,每一句话就是一个小模块。所以说呀 swig 还是很高级的,跟它一个等级的还有 ejs 吧,大概。
然后在生成 html 之后,会先按照 escape 和 em 的规则自己替换一通转义符,导致后面有些公式符号也被替换了,mathjax 表示哭晕在厕所。所以要在自己的 node_modules 里面找到替换规则,换一个正则表达式,好跳过 “$$”、 “__” 这种公式必须的东西。