This commit is contained in:
Cai
2025-09-28 21:33:00 +08:00
parent a24df620b3
commit dc0eeaa933
9 changed files with 532 additions and 187 deletions

View File

@@ -3,8 +3,10 @@ from flask import Blueprint, jsonify, current_app, send_from_directory
from ..services.markdown_service import (
convert_markdown_to_html, wrap_with_styles,
save_html, copy_images, load_markdown_file
)
from markdown_it import MarkdownIt
from mdit_py_plugins import texmath
bp = Blueprint("markdown", __name__)
@@ -12,15 +14,17 @@ bp = Blueprint("markdown", __name__)
def convert_md(course_id, chapter_name, lesson_name):
print(f"convert_md: {course_id}, {chapter_name}, {lesson_name}")
md_file = load_markdown_file(course_id, chapter_name, lesson_name)
# 转换 markdown -> html
html = convert_markdown_to_html(md_file)
# 配置Markdown解析器,启用数学公式支持
md = MarkdownIt()
md.use(texmath.texmath_plugin) # 添加数学公式插件
# 转换markdown为html包含公式标记
html = md.render(md_file)
# 包装样式时添加MathJax支持用于在浏览器中渲染公式
html_with_styles = wrap_with_styles(html)
# 保存 HTML 文件到 static
html_output_path = os.path.join(current_app.config["STATIC_DIR"], f"{chapter_name}-{lesson_name}.html")
# 保存HTML文件到static
html_output_path = os.path.join(current_app.config["STATIC_DIR"], f"{course_id}-{chapter_name}-{lesson_name}.html")
save_html(html_with_styles, html_output_path)
return jsonify({"html_url": f"/static/{chapter_name}-{lesson_name}.html"})
return jsonify({"html_url": f"/static/{course_id}-{chapter_name}-{lesson_name}.html"})
# 提供静态文件访问
@bp.route("/static/<path:filename>")
@@ -28,3 +32,34 @@ def serve_static(filename):
return send_from_directory(current_app.config["STATIC_DIR"], filename)
def wrap_with_styles(html_content):
# 在HTML中添加MathJax支持
mathjax_script = """
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
MathJax.config = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
</script>
"""
# 包装HTML内容和样式
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- 你的其他样式 -->
{mathjax_script}
</head>
<body>
{html_content}
</body>
</html>
"""