Hugo添加数学公式支持#
刚好要用,索性解决了,基于KaTeX。差不多算完美支持数学公式,行内和行间公式都不需要修改或添加Shortcodes
可以直接解析。唯一的缺点是*
这种和markdown语法本身存在双重定义的符号,需要进行转义\*
。
1. 修改extend_head.html#
以下都以网站根目录作为当前路径进行说明:
如果layouts/partials/extend_head.html
存在,则直接在最后进行添加;如果不存在,则新建该路径并复制指定文件到该目录进行编辑。命令如下:
1
2
|
cp themes/PaperMod/layouts/partials/extend_head.html layouts/partials/extend_head.html \
&& nano layouts/partials/extend_head.html
|
根据KaTeX文档《Auto-render Extension》添加如下内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
{{ if or .Params.math .Site.Params.math }}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
integrity="sha384-bYdxxUwYipFNohQlHt0bjN/LCpueqWz13HufFEV1SUatKs1cm4L6fFgCi1jT643X" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"
integrity="sha384-Qsn9KnoKISj6dI8g7p1HBlNpVx0I8p1SvlwOldgi3IorMle61nQy4zEahWYtljaz"
crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05"
crossorigin="anonymous"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
renderMathInElement(document.body, {
// customised options
// • auto-render specific keys, e.g.:
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\(', right: '\\)', display: false },
{ left: '\\[', right: '\\]', display: true }
],
// • rendering keys, e.g.:
throwOnError: false
});
});
</script>
{{ end }}
|
2. 使用方法#
在要用数学公式的文章的front matter
添加如下字段即可使用:
1
|
math: true # 是否开启mathjax
|
同时可以在archetypes/defaults.md
里加入上面的设置,这样每次创建新文章时都会自动添加该字段。另外将true
改为false
,即可在该文章中关闭数学公式功能。
使用格式和Markdown数学公式的格式一样,需要注意一下存在转义的字符,下面是一个例子,转义*
写作\*
。
1
|
$$0.414213562373095048\approx6\*16^{-1}+a\*16^{-2}+0\*16^{-3}+\cdots$$
|
$$0.414213562373095048\approx6*16^{-1}+a*16^{-2}+0*16^{-3}+\cdots$$