Hugo is a powerful static site generator that I use to create this website. When writing technical content, I often need to reference files from Github repositories. Traditionally, this presented two less-than-ideal options:
- Link directly to the file on Github, forcing readers to leave my website and disrupting their reading experience
- Copy and paste the file contents into my blog post, which would become outdated as soon as I update the source file in the repository
I created a custom Hugo shortcode, which are reusable content snippets that can be embedded in your Hugo website, that dynamically fetches and displays content from Github:
{{ $url := printf "https://api.github.com/repos/%s/contents/%s" (.Get "repo") (.Get "path") }}
{{ $lang := default "plaintext" (.Get "lang") }}
{{ with resources.GetRemote $url }}
{{ with transform.Unmarshal .Content }}
{{ highlight (.content | base64Decode) ($lang) "" }}
{{ end }}
{{ end }}
The beauty of this approach is that I’m actually using this same shortcode to display its own implementation above! The shortcode works by fetching the remote content from Github and rendering it directly in your blog post, ensuring your content stays synchronized with your repository.
How to Use the Shortcode
To display Github content in your own Hugo posts, use the following syntax:
{{< github-content
repo="github-user-name/repo-name"
path="path/to/file.json"
lang="json" >}}
The shortcode accepts three parameters:
repo
: Your Github repository in the format “username/repository-name”path
: The path to the file within the repositorylang
: The language of the content for syntax highlighting (e.g., json, python, html)
Note: To show the shortcode syntax above without Hugo processing it, I used the escape sequences. This technique comes from this helpful blog post by Liatas.
Conclusion
This solution has become my preferred method for referencing Github content in my blog posts. It maintains a clean reading experience while ensuring content stays current with minimal maintenance effort. Give it a try in your own Hugo website!
Feel free to use and adapt this shortcode for your own needs. If you have any questions or suggestions for improvements, don’t hesitate to reach out.