I’m writing tutorials for a library in Hugo and find that I am frequently copy/pasting snippets of functional example code into my tutorials. Has anyone thought or otherwise developed a method to include code snippets directly from source files? For example, Doxygen the \snippet command to do something similar to this.
You can use readFile and write your own shortcode: https://gohugo.io/templates/files/#readfile-example-add-a-project-file-to-content
Indeed. The problem isn’t reading the files, it is extracting snippets from the code. I suppose I could use readFile combined with some regular expression magic to make it happen within a shortcode; however, that’s less than ideal.
For the moment, I’m parsing the files ahead of time with SED and generating snippet files that are included with readFile. I’m hoping the Hugo gurus here might have a different idea than what I’ve described above.
This is how I did it.
parameters:
- 
from/tocorresponding to the line numbers
- filepath
then in the actual shortcode:
- 
readFilefilepath
- 
splitthe file at line breaks
- 
rangethrough thelinesprinting out only the lines betweenfrom/to
It did a bunch of other things, but that’s the main bit.
Here’s what I ended up doing:
- I wrote a Python script that recursively reads a source tree and searches for Doxygen-style \snippettags in the source code. It extracts the snippets to thedata/snippetsdirectory. If an error is found while parsing the snippet, the script errors out. The snippets are named using aFilename.Extention_SnippetName.txtconvention.
- I wrote a shortcode that takes Filename SnippetNameas arguments. The shortcode usesreadFileto search for the corresponding snippet. It errors out if the snippet doesn’t exist.
- I wrote an external build script that calls the Python file followed by Hugo.
Although this is far from ideal, it is reasonably extensible if future versions of Hugo would permit more flexible files parsing techniques.