When writing a technical blog you often want to include code snippts inside your blog posts, however you do not want to have to do tedious copy and paste between your actual code and the blog posts. Also you want to ensure that your code actually compiles. There is nothing more annoying then code samples that does not compile.
In order to cope with this I have crated a shortcode
code for hugo that allows me to
- read a file with a given
file
from the filsystem - optional only read from
start
to end
- highlight is as the extension of the file, or optionaly as
language
- show line numbers
- optionaly highlight some
hl_lines
line numbers - works with chroma build in styling (not highlightjs)
The shortcode`s code is as follows: (using the shortcode to show itself)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| {{ $fileName := .Get "file" }}
{{ $extension := path.Ext $fileName }}
{{ $extension := replace $extension "." "" }}
{{ $lang := default $extension (.Get "language") }}
{{ $file := $fileName | readFile }}
{{ $highlight := .Get "hl_lines" | printf "hl_lines=[%s]," }}
{{ $start := 1 }}
{{ if .Get "start" }}
{{ $start := .Get "start" | int }}
{{ $end := .Get "end" | int }}
{{ $length := sub $end $start }}
{{/* Splitting content by newline */}}
{{ $file := split $file "\n" }}
{{/* Limit the array/slice, start from 2nd item then grab all first 3 item */}}
{{ $file := first $length (after $start $file) }}
{{/* Delimit by newline */}}
{{ $file := delimit $file "\n" }}
{{ end }}
{{ (print "```" $lang " {linenos=table," $highlight "linenostart=" $start " }\n" $file "```") | safeHTML }}
|
See also