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 #
---
title: include.html
description: learn how to use the literal shortcode
---
<!--start -->
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.
{{<notice snack>}}
This document is going to be a bit meta.
{{</notice>}}
## How it works
The `{{%/*include*/%}}` shortcode accepts 3 **positional** args: `lang`, `start`, and `stop`. All are optional.
{{<notice warning "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.
{{</notice>}}
### Examples
### This file
{{%include "reference/layouts/shortcodes/include.md" "md" %}}
### Python file with comments
{{%include "static/demo-package.py" "python" "# Start 1" "# End 1" %}}
## Source code
{{%include "layouts/shortcodes/include.html" "go" %}}
Python file with comments #
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 + arg2
Source code #
{{ $path := .Get 0 }}
{{ $lang := .Get 1 | default "s" }}
{{ $start := .Get 2 | default nil }}
{{ $stop := .Get 3 | default nil}}
{{ $content := readFile $path }}
{{ $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 }}