Hugo short codes for code snippets
How to add code samples in your Hugo site
This article will cover how to add code samples from a directory directly into your markdown documentation.
This is useful to keep your code snippets up to date as well as run unit tests in isolation on the code samples.
Create your shortcodes snippet
In the folder directory, layouts/shortcode/
create a file called include.html
.
In your newly created file, add the following code.
{{ $file := .Get 0 }}{{ $file | readFile | safeHTML }}
Save your file.
Reference your content
In a markdown file, reference that function and a path to your code sample.
For example:
{{% include “samples/hello-world.go” %}}
To include syntax highlighting, include the code blocks followed by your languages name.
```go{{% include “samples/hello-world.go” %}}```
Your code sample will now be included in your markdown file with syntax highlights when you build your Hugo site.