How to include code snippet from a file?

There is a standardized short code to include GitHub gist.
Why is there no standardized shortcode to include from a file in the same directory?

Similar to how {{< figure … can reference a file, why can’t one just include a code snippet this way?

There are multiple discussions around this already, and the suggestion has always been to write your own custom shortcode.

Every embedded template has a cost: implementation, testing, maintenance, documentation, and support. To merit inclusion the requirement must be common and the implementation non-trivial. What you describe is neither.


With this content structure:

content/
├── posts/
│   ├── post-1/
│   │   ├── example.go
│   │   └── index.md
│   └── _index.md
└── _index.md

And this shortcode:

layouts/shortcodes/get-page-resource-content.html
{{- with $path := .Get 0 }}
  {{- with $.Page.Resources.Get $path }}
    {{- .Content | strings.TrimSpace | safeHTML }}
  {{- else }}
    {{- errorf "The %q shortcode was unable to find %s: see %s" $.Name $path $.Position }}
  {{- end }}
{{- else }}
  {{- errorf "The %q shortcode requires a single positional parameter, the path to the file within the current page bundle. See %s" .Name .Position }}
{{- end -}}

You can use either of these approaches to highlight the example code:

{{< highlight "go" >}}
{{% get-page-resource-content example.go %}}
{{< /highlight >}}

```go
{{% get-page-resource-content example.go %}}
```

This is just one of several ways to do this, which is another reason to set the bar high for embedding a template: they are opinionated, and will rarely make everyone happy.

2 Likes

Thanks @jmooring this is awesome.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.