如何在Blogster模板中实现Markdoc行内数学公式渲染?
实现Blogster模板中行内数学公式渲染
问题
使用Blogster模板时,无法直接渲染$A \ge B$这类数学公式。之前找到的方案虽能渲染公式,但所有公式均为换行显示,需要改成行内展示的效果。
解决方案
问题根源在于原MathFormula组件使用react-markdown时,默认会将内容包裹在块级<p>标签中,导致公式独占一行。以下是两种修复方案:
方案一:直接使用KaTeX渲染行内公式
这种方式更轻量,无需依赖react-markdown,直接调用KaTeX的API渲染行内公式:
- 安装KaTeX(若未安装):
npm install katex # 或 yarn add katex
- 修改
src/components/MathFormula.tsx:
import 'katex/dist/katex.min.css'; import katex from 'katex'; import { useEffect, useRef } from 'react'; export function MathFormula({ formula }: { formula: string }) { const formulaRef = useRef<HTMLSpanElement>(null); useEffect(() => { if (formulaRef.current && formula) { katex.render(formula, formulaRef.current, { throwOnError: false, // 忽略渲染错误,避免页面崩溃 displayMode: false, // 关键:设为false启用行内模式 }); } }, [formula]); return <span ref={formulaRef} className="inline-katex" />; }
方案二:修改react-markdown的输出为行内元素
如果想继续使用react-markdown,只需将默认生成的块级<p>标签替换为行内<span>:
修改src/components/MathFormula.tsx:
import 'katex/dist/katex.min.css'; import Markdown from 'react-markdown'; import rehypeKatex from 'rehype-katex'; import remarkMath from 'remark-math'; export function MathFormula({ formula }: { formula: string }) { return ( <Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex]} components={{ // 将默认的<p>块级标签替换为<span>行内标签 p: ({ children }) => <span>{children}</span>, }} > {formula} </Markdown> ); }
验证
在博客md文件中保持原有写法:
would boost from {% mathFormula formula="$O(1)$" /%} to O(N) given is the size of the RAM
修改后,$O(1)$会以行内形式嵌入文本中,不再单独换行。
内容的提问来源于stack exchange,提问作者GUA
相关产品推荐
相关产品推荐

