概述
在Hugo
的PaperMod
的主题中加入数学公式支持是很多人的刚需,在此主题下最好的文章是PaperMod
开发者给出的Math Typesetting 。根据此篇博客内容,我们发现加入数学公式功能需要对theme
文件夹进行修改,但大部分人可能都使用了git submodule
引入的主题文件。这使我们几乎无法通过修改主题文件来增加这一功能。
本文主要讨论了在使用submodule
情况下,不通过修改主题文件加入数学公式支持。
解决方案
在当前的写作仓库内创建layouts/partials/math.html
文件,写入以下内容:
<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>
对于此文件中的内容,我参考了Katex 文档中给出的代码。此配置与mathjax
的使用是一致的。当然对于css
和script
中的引用链接读者可以自行修改为其他CDN或自行部署以提高访客的阅读体验。
然后创建layouts/partials/extend_head.html
文件,写入以下内容:
{
{ if or .Params.math .Site.Params.math }}
{
{ partial "math.html" . }}
{
{ end }}
最终,我们会获得如下目录结构:
读者可前往我的博客查看具体结构。
当我们确认某一篇博客需要加入数学公式支持时,我们需要在markdown
文件键入以下内容:
---
title:
date:
tags:
math: true
---
此实例中的title
等变量需要读者自行补齐。
读者可以通过$\vec{F}$
实现 F ⃗ \vec{F} F 的行内显示的效果。
当然读者也可以通过以下代码:
x = \begin{cases}
a &\text{if } b \\\
c &\text{if } d
\end{cases}
实现如下块状显示的效果:
x = { a if b c if d x = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases} x={
acif bif d
注意由于
hugo
会对字符进行转译,我们不能使用\\
进行换行而需要使用\\\
。
关于katex
支持的latex
函数,读者可以自行参考function 文档和Support Table。
拓展
当我们在配置文件内写入enableInlineShortcodes: true
后,这意味着我们几乎可以在博客文章内引入和运行一切javascript
文件且不影响其他博客文章。这大大增加了PaperMod
的可拓展性。下图展示了我在博客内引入nutshell插件的情况:
为达成此目的,我们只需要在博客头部加入以下代码:
{
{< nutshell.inline >}}
<script src="https://cdn.jsdelivr.net/gh/ncase/[email protected]/nutshell.js"></script>
{
{</ nutshell.inline >}}
此处的{
{< nutshell.inline >}}
中的nutshell
可以替换为其他字符。