在 HUGO 帖子中包含来自 repo 的源文件

Including source files from a repo in HUGO posts

我正在用 HUGO 建立一个博客,作为一个注释代码回购,并且我在 post 上包括直接来自回购的源文件。

我已经能够使它达到工作状态并想改进它,但我被卡住了。

我做了什么

在 HUGO 站点根目录中有一个 .gitignore'd repos 目录,其中包含源代码 repos。

有一个getSourceFile.html简码:

{{ with .Get 0 }}
<pre><code>{{ readFile . }}</code>
<span class="source-footer">{{.}}</span>
</pre>
{{ end }}

然后,在 post 我可以像这样使用简码:

#### Base/EntityTypeConfiguration.cs

Estas clases permiten manejar una clase de configuración por cada clase del modelo...

{{< getSourceFile "repos/EFCoreApp/src/EFCore.App/Base/EntityTypeConfiguration.cs" >}}

我明白了:

非常好,因为我不必复制和粘贴代码,它是 100% 最新的,我确信它可以编译。

但这就是我卡住的地方!

我想做什么

1) 在 front matter 中设置 repo root 以便简码更易于使用,如下所示:

{{< getSourceFile "src/EFCore.App/Base/EntityTypeConfiguration.cs" >}}

2) 能够将语言作为参数传递给短代码以在突出显示功能中使用它,类似这样(这不起作用):

{{< getSourceFile "src/EFCore.App/Base/EntityTypeConfiguration.cs" "csharp" >}}

getSourceFile.html:

{{ with .Get 0 }}
```{{.Get 1}}
<pre><code>{{ readFile . }}</code>
<span class="source-footer">{{.}}</span>
</pre>
```
{{ end }}

或者更好的是,从文件扩展名推断出来! ;-)

我认为这应该不会太难,但这是我第一次使用 Hugo、Go 和模板,所以,有人可以帮我解决这个问题吗?

提前致谢。

我终于在HUGO's dicussion forum得到了答案,所以我只想post在这里完成这个问题。

这是最终简码:

{{ $file := .Get 0 }}
{{ $repoFilePath := printf "%s/%s" $.Page.Params.reponame $file }}
{{ $repoFile := printf "repos/%s" $repoFilePath }}
{{ $fileExt := replace (index (findRE "(\.)\w+$" $file) 0) "." "" }}
<pre><code class="language-{{ $fileExt }}">{{ readFile $repoFile }}</code>
<span class="source-footer">{{ $repoFilePath }}</span>
</pre>

这甚至解决了文件扩展名的语言突出显示问题。