by Jason Han

Hugo 问题汇总

1. 如何在Hugo中插入Mermaid流程图

Mermaid是Markdown中最常用的绘制流程图的方式之一。不过,在某些Hugo模板中,并不能直接正常显示Mermaid流程图。解决办法如下1,2

  1. themes/(你的模板名称)/layouts/中增加shortcodes文件夹,并创建文件mermaid.html
<script async src="/js/mermaid.js"></script>
<div class="mermaid">
{{ .Inner }}
</div>

此处对于mermaid.js脚本设置的async,即流程图与网页的其余部分异步执行,提高整个页面的显示效果

  1. 下载 mermaid.js (与上述代码片段中的文件名对应),并添加至themes/(你的模板名称)/static/js/文件夹。
  2. 在绘制流程图时,不再```mermai开头和```结尾;而是以{{<mermaid>}}开头,以{{</mermaid>}}结尾。
  3. 需要注意的是,在设置图类型的一行的末尾,要加上分号,如 graph TD;。不过这一点据说也因mermaid 的版本而异。

2. 如何在Hugo中插入公式

利用Hugo写的文章无法直接正常的显示数学公式,不过Hugo支持使用MathJax对数学公式进行渲染,Hugo官方提供了相应的配置方法3。不过,经过测试,这种方法很多情况下不能奏效,经多方尝试,文献 4 提供的方法是可行的,总结如下:

  1. 在模板的 layouts/partials/ 路径下创建 mathjax.html 文件,内容为:
<script type="text/javascript"
async
src="https://cdn.bootcss.com/mathjax/2.7.3/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
displayMath: [['$$','$$'], ['\[\[','\]\]']],
processEscapes: true,
processEnvironments: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'],
TeX: { equationNumbers: { autoNumber: "AMS" },
extensions: ["AMSmath.js", "AMSsymbols.js"] }
}
});

MathJax.Hub.Queue(function() {
// Fix <code> tags after MathJax finishes running. This is a
// hack to overcome a shortcoming of Markdown. Discussion at
// https://github.com/mojombo/jekyll/issues/199
var all = MathJax.Hub.getAllJax(), i;
for(i = 0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>

<style>
code.has-jax {
font: inherit;
font-size: 100%;
background: inherit;
border: inherit;
color: #515151;
}
</style>
  1. 在模板的 layouts/partials/footer.html 文件最后追加一句:
{{ partial "mathjax.html" . }}

3. 在Hugo中插入矩阵不能正常显示

虽然在 Hugo 能插入公式,但是当插入矩阵时,其显示可能出问题,如:

当输入以下代码时:

$$
\begin{matrix}
1 & x & x^2 \\
1 & y & y^2 \\
1 & z & z^2 \\
\end{matrix}
$$

显示可能为: $$ \left[\begin{matrix} 1 & x & x^2 \
1 & y & y^2 \
1 & z & z^2 \
\end{matrix} \right] $$ 尝试了参考 5 的办法,在上述代码片段前后分别加上<div></div>可正常显示,如下:

$$ \left[\begin{matrix} 1 & x & x^2 \\ 1 & y & y^2 \\ 1 & z & z^2 \\ \end{matrix} \right] $$

4. 点击标题连接后显示未找到页面

可能是因为文件命名时是存在特殊符号,如“#”,在写C#相关的文章是,需要注意可以把文件名称中的#替换成“Sharp”。

参考


  1. https://osgav.run/lab/hugo-mermaid-diagrams.html ↩︎

  2. https://www.hairizuan.com/rendering-diagrams-in-hugo/ ↩︎

  3. https://www.gohugo.org/doc/tutorials/mathjax/ ↩︎

  4. https://note.qidong.name/2018/03/hugo-mathjax/ ↩︎

  5. https://github.com/gohugoio/hugo/issues/2893 ↩︎

This page and its contents are copyright © 2021, Jason Han.