这种情况发生在我的开发环境中,也出现在实时的 Discourse 论坛 https://discourse.gohugo.io/ 以及 Discourse 演示站点上。
通常,当围栏代码块未设置语言时,我们会进行自动检测。在常规的 Highlight.js 使用场景(Node.js 或浏览器)中,这总能成功,因为它总会选中某种语言。
Discourse 似乎将此类代码块保存为 <code class="lang-auto">,这并不是一个有效的语言标识符 ![]()
我与 AI-Bot ask.discourse.cm…30386 进行了交流:
它指出你们在运行时进行了一些“魔法”操作,移除 “lang-auto” 后让 highlight.js 重新执行自动检测。看起来这个更新并非总是在 highlight.js 处理代码之前发生。因此,这似乎是 Discourse 中 highlight.js 集成和自动检测实现的一个小缺陷。
取消设置默认语言也不起作用,因为这样 “移除 lang-auto” 的操作就会失效,而且看起来 Discourse 的方式不会重新执行自动检测。
- 手动设置语言始终有效——无论是内置语言,还是通过 PluginAPI (registerHLJSLanguage) 作为主题组件添加的自定义语言(hugo-templates)。
- 如果不设置语言,结果取决于 content() 的竞态条件和时序,导致失败。
将默认语言设置为 “text” 也不是办法,因为我们希望代码被高亮显示,并且为了可用性需要自动检测功能(而且它是有效的…)
下面是一个 Markdown 示例,其中第二个代码块会失败(当然,前提是默认语言设置为 “auto”)。在 https://try.discourse.org/ 上使用以下 Markdown 可以轻松复现:
并在 24 小时内:Failed Discourse Autodetection breaks rendering of fenced code blocks - support - Discourse Demo
# 这个有效
```
{{ $currentPagemd5 := md5 $currentPage.File.Path }}
{{ $currentPagemd5ext := (print $currentPagemd5 ".json")}}
```
# 这个失败并分配了 "lang-auto"
```
{{ $currentPage := . }}
{{ $jsonFile := "" }}
{{ with $currentPage.File }}
{{ $currentPagemd5 := md5 $currentPage.File.Path }}
{{ $currentPagemd5ext := (print $currentPagemd5 ".json")}}
{{ $files := readDir "data/commits/" }}
{{if gt (len $files ) 0}}
<div class="bord-bas"></div>
<div>
<details>
<summary>页面变更</summary>
<div>
{{ range $files }}
{{ if eq .Name $currentPagemd5ext }}
{{ $jsonFile := $currentPagemd5 }}
{{ $data := index $.Site.Data.commits $jsonFile }}
<ul>
{{ range $data }}
<li>
{{ dateFormat "02/01/2006" .commit_date }} : {{ trim .message "\n" }} ({{ .author }})
</li>
{{ end }}
</ul>
{{ end }}
{{ end }}
</div>
</details>
</div>
{{ end }}
{{ end }}
```
