Embed files in blog posts

Philipp | Sep 25, 2022

Shortcode to embed files in blog posts

In my posts, I write about the things I’m programming in my free time and often I want to show the code. Therefore I need an easy way to include the files as code preview in my blog posts.

I use a shortcode which makes use of HUGOs readFile and saveHtml function.

include.html

{{- $resource := $.Page.Resources.GetMatch (.Get 0) -}}
{{- if $resource -}}
    {{- $resource.Content | safeHTML -}}
{{- else -}}
    {{- .Get 0 | readFile | safeHTML -}}
{{- end -}}

and you use it like this:

    ```html
    {{- $resource := $.Page.Resources.GetMatch (.Get 0) -}}
    {{- if $resource -}}
        {{- $resource.Content | safeHTML -}}
    {{- else -}}
        {{- .Get 0 | readFile | safeHTML -}}
    {{- end -}}
    ```

Furthermore I’d like to have some kind of raw-data view, that allows an easy download of the files, without copy and paste. For this to work, the file has to be in the static folder of your hugo project. Then you can provide the file like this:

[include.html](include.txt)

which results in:

include.html