Skip to content

Commit 0c03cae

Browse files
committed
feat: add an embedded shortcode for code snippets
1 parent 6b1edb4 commit 0c03cae

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

layouts/shortcodes/embedded.html

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
{{ $language := .Get "language" }}
2+
{{ $source := .Get "source" }}
3+
{{ $options := .Get "options" }}
4+
{{ $id := .Get "id" }}
5+
{{ $startTag := printf "START %s" $id }}
6+
{{ $endTag := printf "END %s" $id }}
7+
8+
{{ if and $source (strings.Contains $source "testcontainers-go") }}
9+
{{/*
10+
If the source is a testcontainers-go file, we need to use a different tag. In example:
11+
12+
// runRedisContainer {
13+
// ...
14+
// }
15+
*/}}
16+
{{ $startTag = printf "// %s {" $id }}
17+
{{ $endTag = printf "// }" }}
18+
{{ end }}
19+
20+
{{ with $source | readFile }}
21+
{{ $snippet := . }}
22+
23+
{{ if $id }}
24+
{{ $lines := split $snippet "\n" }}
25+
26+
{{ $startl := -1 }}
27+
{{ $endl := -1 }}
28+
29+
{{/* Find the lines that ends with the start and end tags. */}}
30+
{{ range $index, $line := $lines }}
31+
{{ if hasSuffix (strings.TrimSpace $line) $startTag }}
32+
{{ $startl = $index }}
33+
{{ else if hasSuffix (strings.TrimSpace $line) $endTag }}
34+
{{ $endl = $index }}
35+
{{ end }}
36+
{{ end }}
37+
38+
{{/* Let's add some basic assertions. */}}
39+
{{ if lt $startl 0 }}
40+
{{ errorf "Named snippet '%s' is missing START tag (searched %d lines)" $id (len $lines) }}
41+
{{ end }}
42+
43+
{{ if lt $endl 0 }}
44+
{{ errorf "Named snippet '%s' is missing END tag (searched %d lines)" $id (len $lines) }}
45+
{{ end }}
46+
47+
{{ if le $endl $startl }}
48+
{{ errorf "Named snippet '%s': END tag (line %d) must come after START tag (line %d)" $id $endl $startl }}
49+
{{ end }}
50+
51+
{{/* Size of the snippet in number of lines. */}}
52+
{{ $snippetLen := sub (sub $endl $startl) 1 }}
53+
54+
{{/* Create slice with only the lines between the tags. */}}
55+
{{ $includedLines := first $snippetLen (after (add $startl 1) $lines) }}
56+
57+
{{/* Join the lines into the final snippet. */}}
58+
{{ $snippet = delimit $includedLines "\n" }}
59+
{{ $markdown := printf "```%s\n%s\n```" $language $snippet }}
60+
{{ $markdown | markdownify }}
61+
{{ else }}
62+
{{ $markdown := printf "```%s\n%s\n```" $language . }}
63+
{{ $markdown | markdownify }}
64+
{{ end }}
65+
{{ end }}

0 commit comments

Comments
 (0)