django使用katex将markdown中的公式渲染正确
katex官网:https://katex.org/
katex官网安装教程:https://katex.org/docs/browser.html
其实就是这几行:
<!DOCTYPE html>
<!-- KaTeX requires the use of the HTML5 doctype. Without it, KaTeX may not render properly -->
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-KiWOvVjnN8qwAZbuQyWDIbfCLFhLXNETzBQjA/92pIowpC0d2O3nppDGQVgwd2nB" crossorigin="anonymous">
<!-- The loading of KaTeX is deferred to speed up page rendering -->
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-0fdwu/T/EQMsQlrHCCHoH10pkPLlKA1jL5dFyUOvB3lfeT2540/2g6YgSi2BL14p" crossorigin="anonymous"></script>
<!-- To automatically render math in text elements, include the auto-render extension: -->
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+XBljXPPiv+OzfbB3cVmLHf4hdUFHlWNZN5spNQ7rmHTXpd7WvJum6fIACpNNfIR" crossorigin="anonymous"
onload="renderMathInElement(document.body);"></script>
</head>
...
</html>
为了尽量本地化,我们把他的katex.min.css,katex.min.js还有auto-render.min.js都下载到本地:
那么就直接去下载他的release吧:
github地址:https://github.com/KaTeX/KaTeX/releases
下载下来后
可以发现目录树为:
│ katex.css
│ katex.js
│ katex.min.css
│ katex.min.js
│ katex.mjs
│ README.md
│
├─contrib
│ auto-render.js
│ auto-render.min.js
│ auto-render.mjs
│ copy-tex.css
│ copy-tex.js
│ copy-tex.min.css
│ copy-tex.min.js
│ copy-tex.mjs
│ mathtex-script-type.js
│ mathtex-script-type.min.js
│ mathtex-script-type.mjs
│ mhchem.js
│ mhchem.min.js
│ mhchem.mjs
│ render-a11y-string.js
│ render-a11y-string.min.js
│ render-a11y-string.mjs
│
└─fonts
KaTeX_AMS-Regular.ttf
...
KaTeX_Typewriter-Regular.woff2
我们只需要把katex.min.css,auto-render.min.js,katex.min.js拿到我们的static文件夹下
并且把fonts文件夹全部拿到katex.min.css所在的文件夹下即可。因为这个css会用到这个fonts
我们自己的static文件夹目录树为:
├─article
│ test.md
│
├─css
│ │ katex.min.css
│ │ native.css
│ │
│ └─fonts
│ KaTeX_AMS-Regular.ttf
│ ...
│ KaTeX_Typewriter-Regular.woff2
│
└─js
auto-render.min.js
katex.min.js
article.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/css/native.css">
<link rel="stylesheet" href="/static/css/katex.min.css">
</head>
<body>
{{ article |safe }}
</body>
<script defer src="/static/js/katex.min.js"></script>
<script defer src="/static/js/auto-render.min.js" onload="renderMathInElement(document.body);"></script>
</html>
效果: