Inline code samples are great — but code samples that are pulled from source files can be even better! This {{%include%}} shortcode is inspired by Sphinx’s .. literalinclude:: functionality.
This document is going to be a bit meta.
How it works #
The {{%include%}} shortcode accepts 3 positional args: lang, start, and stop. All are optional.
Don't forget to use %
This shortcode relies on Hugo’s markdown rendering to automatically handle code syntax highlighting. If you surround this shortcode with
< > instead, it will break.Examples #
This file #
md
Python file with comments #
python
def demo_function(arg1, arg2):
"""Demo Function
This function takes two arguments and returns their sum.
Args:
arg1 (int): The first argument.
arg2 (int): The second argument.
Returns:
int: The sum of arg1 and arg2.
"""
return arg1 + arg2Source code #
go
{{ $path := .Get 0 }}
{{ $lang := .Get 1 | default "s" }}
{{ $start := .Get 2 | default nil }}
{{ $stop := .Get 3 | default nil}}
{{ $content := readFile $path }}
{{/* Optional: Log warning for missing files */}}
{{ if and $path (not $content) }}
{{ warnf "Include shortcode: File not found '%s' on page %s" $path .Page.RelPermalink }}
{{ end }}
{{/* Original processing logic - unchanged */}}
{{ $chunked := split $content "\n" }}
{{ $snippet := "" }}
{{ $capture := false }}
{{if eq $start nil }}
{{ $capture = true }}
{{end}}
{{- range $chunked }}
{{ if and (not $capture) (in . $start) }}
{{ $capture = true }}
{{ else if and $capture (in . $stop) }}
{{ $capture = false }}
{{ else if $capture }}
{{ $snippet = print $snippet . "\n" }}
{{ end }}
{{- end }}
{{ printf "```%s\n%s\n```" $lang $snippet | safeHTML }}