Skip to content

Instantly share code, notes, and snippets.

@jbr
Last active December 29, 2021 08:21
Show Gist options
  • Save jbr/b59c5ca43ac30cff27fe037a71ebaedf to your computer and use it in GitHub Desktop.
Save jbr/b59c5ca43ac30cff27fe037a71ebaedf to your computer and use it in GitHub Desktop.
hugo shortcode for including source code from a file and optionally a subset of lines

I couldn't find this anywhere on the internet and struggled to figure out how to do this so I'm hoping github's seo is good enough that it helps someone else.

Files must be within the content dir or the project root, and are relative to those places. Symlinks are followed, though.

I'm not sure which order they're checked, but in the following examples, hugo will look in PROJECT_ROOT/content/code-samples/example.rs and PROJECT_ROOT/code-samples/example.rs and use whichever it finds first.

lines 0-15

{{< code file="code-samples/example.rs" language="rust" to=15 >}}

lines 15-38

{{< code file="code-samples/example.rs" from=15 to=38 >}}

lines 38-end

{{< code file="code-samples/example.rs" from=38 >}}
{{/* this file should live in PROJECT_ROOT/layouts/shortcodes/code.html */}}
{{ $file := .Get "file" | readFile }}
{{ $lines := split $file "\n" }}
{{/* you may want to change this default */}}
{{ $lang := default "rust" (.Get "language") }}
{{ $start := default 0 (.Get "from") }}
{{ $end := default (len $lines) (.Get "to") }}
{{ $output := delimit (after $start (first $end $lines)) "\n" }}
{{ (print "```" $lang "\n" $output "\n```") | markdownify}}
@Aaron-von-Awesome
Copy link

Thank you very much for this! 🤓

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment