在Typecho上渲染LaTeX公式

还在担心你的博客没法渲染$\LaTeX$公式?

之前我试用过MathJax,但是缓慢的渲染速度、没法自定义渲染范围等缺点,使我果断放弃这个渲染程序。

也曾试着部署过$\KaTeX$,但是因为没有配置自动渲染失败了。

昨天照着简洁的文档捣鼓了几下程序,终于千盼万盼盼来了成功渲染。


(左:$\KaTeX$;右:MathJax)

#1.加载资源

将这段代码添加到你的主题的head标签内

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>

如果您正在使用butterfly主题,请使用以下代码,这将使jsdelivr资源和您主题的设置适配。

<link rel="stylesheet" href="https://<?php $this->options->jsdelivrLink() ?>/npm/[email protected]/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">
<script defer src="https://<?php $this->options->jsdelivrLink() ?>/npm/[email protected]/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>
<script defer src="https://<?php $this->options->jsdelivrLink() ?>/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<style>
/*原汁原味的渲染样式*/
.katex .text{
    border:none;
    margin:0;
    background:none;
    padding:0;
    font-size: 17px;
    color:inherit;
}
.katex{
    padding:0 5px;
    color:inherit;
}
</style>

#2.配置$\KaTeX$

<script>
function LoadLatex() {
        renderMathInElement(document.body, {
          delimiters: [
              {left: '$$', right: '$$', display: true},
              {left: '$', right: '$', display: false},//洛谷KaTeX渲染标志
              {left: '\\(', right: '\\)', display: false},
              {left: '\\[', right: '\\]', display: true}
          ],
          throwOnError : false,
          ignoredClasses:['nokatex'],//禁止渲染katex的类
          ignoredTags:["script", "noscript", "style", "input", "textarea", "pre", "code", "option"]//禁止渲染katex的标签/元素
        });
}
    document.addEventListener("DOMContentLoaded",LoadLatex);
</script>

建议的配置:禁止在评论区渲染$\KaTeX$1

pjax回调函数:LoadLatex();

$\KaTeX$官方文档: https://katex.org/docs/api

#3.结语

恭喜,现在你应该成功配置了$\KaTeX$,试着渲染公式吧

$\LaTeX$格式手册: https://katex.org/docs/supported.html
简单参考: https://help.luogu.com.cn/rules/academic/handbook/latex


  1. 防止迭代轰炸

标签: 博客, 教程

许可协议

本文作者 , 采用 CC-BY-SA-4.0 许可协议,转载请注明出处。

已有 3 条评论

添加新评论

  1. changwenxuan changwenxuan

    怎么设置不在讨论区渲染啊

    1. 改renderMathInElement函数第二个参数里的ignoredClasses,加上讨论区的类

      有时间帮你看看你哪个主题怎么配置吧

      以及像这种测试评论建议在设置里删除的(