[英]Rendering HTML properly including math tags
When a user designs something in CKEditor5, I save data in the database as a string.当用户在 CKEditor5 中设计某些东西时,我将数据库中的数据保存为字符串。 Sample string from database record:来自数据库记录的示例字符串:
<p>What is the result of following?</p><p><math xmlns="http://www.w3.org/1998/Math/MathML"><msqrt><mn>16</mn></msqrt><mo> </mo><mo>+</mo><mo> </mo><mfrac><mn>3</mn><mn>9</mn></mfrac><mo> </mo><mo>=</mo><mo> </mo><mo>?</mo></math></p>
My question is about rendering html.我的问题是关于渲染 html。 I could parse the whole html string using the 'html-react-parser'
package perfectly if it doesn't include <math/>
tags.如果不包含<math/>
标签,我可以使用'html-react-parser'
package 完美地解析整个 html 字符串。 It did not parse <math/>
tags and people suggested the 'react-mathjax-preview'
package.它没有解析<math/>
标签,人们建议使用'react-mathjax-preview'
package。
But when I parsed the whole html string with that, it parsed perfectly but then other html tags created on CKEditor5 looked like plain text.但是当我用它解析整个 html 字符串时,它解析得很好,但是在 CKEditor5 上创建的其他 html 标记看起来像纯文本。 So I decided to convert the string to html with "DomParser()" and then loop in its "childNodes" searching if it has a math tag.因此,我决定使用“DomParser()”将字符串转换为 html,然后在其“childNodes”中循环搜索是否有数学标签。 Then I parsed each one separately with ( parse()
or <MathJax/>
)然后我用( parse()
或<MathJax/>
)分别解析每一个
import MathJax from 'react-mathjax-preview';
const MathjaxParser = ({ mString }) => {
return <MathJax id="math-preview" math={mString} />;
};
export default MathjaxParser;
. .
import React from 'react';
import parse from 'html-react-parser';
import MathJax from 'app/components/MathjaxParser';
const Parser = ({ mString }) => {
const iparser = new DOMParser();
const parsedHtml = iparser.parseFromString(mString, 'text/html');
const itemsArray = [];
if (!parsedHtml || !parsedHtml.body) return null;
parsedHtml.body.childNodes.forEach(item => {
let type = 'normal';
if (!item.outerHTML) return;
if (item.outerHTML.includes('xmlns="http://www.w3.org/1998/Math/MathML')) {
type = 'math';
}
itemsArray.push({ type, html: item.outerHTML });
});
return (
<div className="cursor-pointer">
{itemsArray.map((item, index) =>
item.type === 'math' ? (
<MathJax key={index} mString={item.html} />
) : (
<div key={index}>{parse(item.html)}</div>
)
)}
</div>
);
};
export default Parser;
In anywhere of the project, I render it like:在项目的任何地方,我将其渲染为:
import Parser from 'app/components/Parser';
..........
return ( <Parser mString={stringHTML} /> );
But I think it is a workaround and I would like to ask what is the correct way you suggest?但我认为这是一种解决方法,我想问一下你建议的正确方法是什么?
react-mathjax-preview VERSION - 2.1.3 will resolve this issue. react-mathjax-preview VERSION - 2.1.3 将解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.