使用KaTeX或MathJax渲染TeX

时间:2016-10-08 09:24:20

标签: javascript node.js mathjax tex katex

我有一个HTML文档

<div>
  <p>One paragraph</p>
  <p>Another paragraph</p>
</div>

在某些段落中,我有

<p>Some text and a formula $a = b + c$.</p>

我希望带有$ -signs的文本使用KaTeX呈现为TeX数学。

问题是,如果我想在浏览器中使用它,我必须使用

katex.render("c = \\pm\\sqrt{a^2 + b^2}", element);

所以我需要分配一个元素。

我应该像这样编写我的html文档,还是有其他选择:

<div>
  <p>One paragraph</p>
  <p>Another paragraph</p>
  <p>Some text and a formula <span id="firstFormula"></span>.</p>
  <p>More text and another formula <span id="secondFormula"></span>.</p>
</div>
<script>
  const firstFormula = document.getElementById('firstFormula');
  katex.render("c = \\pm\\sqrt{a^2 + b^2}", firstFormula);

  const secondFormula = document.getElementById('secondFormula');
  katex.render("c = \\pm\\sqrt{a^2 + b^2}", secondFormula);
</script>

并为每个公式重复相同的模式?

我不能只编写文本并用tex渲染输出替换所有文本公式,这似乎有点奇怪。

例如,可汗学院如何在this page上将文字和公式结合起来?他们是否在服务器上呈现所有内容并将其发送给客户端?

在这种情况下使用MathJax会更好吗?我对KaTeX更加热衷,因为它更快。

1 个答案:

答案 0 :(得分:1)

默认情况下,MathJax不使用$作为分隔符。所以你必须手动配置它们。

以下使用MathJax的示例来自其documentation

<!DOCTYPE html>
<html>
<head>
<title>MathJax TeX Test Page</title>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript" async
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML">
</script>
</head>
<body>
When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</body>
</html>

如果你想使用KaTeX,你需要包含脚本来自动渲染并使用$作为分隔符。有关说明,请参阅https://github.com/Khan/KaTeX/blob/master/contrib/auto-render/README.mdHere就是一个例子。