问题
I have a html document
<div>
<p>One paragraph</p>
<p>Another paragraph</p>
</div>
and in some of the paragraphs, I have
<p>Some text and a formula $a = b + c$.</p>
and I want the text withing the $-signs to be rendered as TeX math using KaTeX.
The problem is that if I want to use it in the browser, I have to use
katex.render("c = \\pm\\sqrt{a^2 + b^2}", element);
so I need to assign an element.
So should I really write my html document like this or are there any other options:
<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>
and repeat the same pattern for each formula?
It seems a bit weird that I cannot just write the text and replace all the text formulas with tex rendered output.
How does, for instance, Khan Academy do it on this page where they combine text and formulas? Do they render everything on the server and send it to the client?
Is it better to use MathJax in this situation? I am just more keen on KaTeX since it is much faster.
回答1:
By default, MathJax doesn't use $
as delimiters. So you'll have to configure them manually.
The following example using MathJax is from its 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>
If you want to use KaTeX, you'll need to include the script to auto render and make it use $
as delimiters. See https://github.com/Khan/KaTeX/blob/master/contrib/auto-render/README.md for instructions. Here is an example.
来源:https://stackoverflow.com/questions/39930756/render-tex-with-katex-or-mathjax