Search code examples
hugohugo-shortcode

Including source files from a repo in HUGO posts


I'm setting up a blog with HUGO, as a commented code repo, and I'm including source files right from the repos on the posts.

I've been able to get it to a working condition and want to improve it but I'm stuck.

What I've done

There's a .gitignore'd repos dir inside the HUGO site root, that holds the source code repos.

There's a getSourceFile.html shortcode:

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

Then, in the post I can use the shortcode like so:

#### 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" >}}

and I get this:

Which is pretty nice, since I don't have to copy and paste code, it's 100% up to date and I am sure it compiles.

But this is where I'm stuck!

What I would like to do

1) Setting up the repo root in the front matter so the shortcode is simpler to use, like so:

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

2) Being able to pass the language as a parameter to the shortcode to use it in the highlighting feature, something like so (this does not work):

{{< 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 }}

Or better yet, infer it from the file extension! ;-)

I think it shouldn't be too difficult but this is my first experience with Hugo, Go and the Templates, so, Could someone help me with this, please?

Thanks in advance.


Solution

  • I finally got the answer in HUGO's dicussion forum, so I just wanted to post it here to finish the question.

    This is the final shortcode:

    {{ $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>
    

    And this even solves the language highlighting from the file extension.