如何在我的Next.js应用程序中集成Mathcraft,以便使用Latex渲染内联和显示方程?

hxzsmxv2  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(100)

我想在我的nextjs应用程序中集成Mathcraft。我使用nextjs 13并使用应用程序目录进行路由我想在服务器中渲染我的代码,所以当用户打开页面时不需要重新渲染。我试图阅读文档,但仍然缺乏信息。
我想得到Some inline equation $x^2-2x+5=0$ will render inline.Some display equation using duble dollar $$x^2-2x+5=0$$ will render display.
这是我的准则

import { mathjax } from 'mathjax-full/js/mathjax.js';
import { TeX } from 'mathjax-full/js/input/tex.js';
import { SVG } from 'mathjax-full/js/output/svg.js';
import { liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor.js';
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html.js';

const inputTex = 'Persamaan $c = \\pm\\sqrt{a^2 + b^2}$';

const adaptor = liteAdaptor();
RegisterHTMLHandler(adaptor);

const tex = new TeX();
const svg = new SVG();
const html = mathjax.document('', { InputJax: tex, OutputJax: svg });

// Mode inline
const nodeInline = html.convert(inputTex, { display: false });
const svgCodeInline = adaptor.outerHTML(nodeInline);

// Mode display
const nodeDisplay = html.convert(inputTex, { display: true });
const svgCodeDisplay = adaptor.outerHTML(nodeDisplay);

export default function page() {
    return (
    <>
        <span dangerouslySetInnerHTML={{ __html: svgCodeInline }}></span>
        <span dangerouslySetInnerHTML={{ __html: svgCodeDisplay }}></span>
    </>
    )
}

字符串
但这将转换所有的文本,而不仅仅是公式之间的$。这是样本输出Render all text任何人都可以帮助我?

4ngedf3f

4ngedf3f1#

您可以使用此函数仅呈现$$之间的等式:

export function RenderLatex(latex) {
  let result = latex.split("");
  let firstPos = null;
  let firstFounded = false;
  let returnString = latex;
  for (let i = 0; i < latex.length; i++) {
    if (latex[i] === "$" && !firstFounded) {
      firstFounded = true;
      firstPos = i;
    }
    if (firstFounded && i < 1 && firstPos === i - 1)
      firstFounded = false;
    else if (latex[i] === "$" && firstFounded && i !== firstPos) {
      firstFounded = false;
      result[firstPos] = ""
      result[i] = ""
      let firstPart = result.join("").slice(0, firstPos);
      let secondPart = result.join("").slice(i, result.join("").length);
      let addition = MathJax.tex2chtml((result.join("").substring(firstPos, i))).outerHTML;
      return RenderLatex(firstPart + addition + " " + secondPart)
    }
  }
  return returnString;
}

字符串

相关问题