Problem: Hugo can not simply include other files from your page bundle.
Solution: $.Page.Dir
, path.Join
, readFile
I usually organize larger posts in folders, e.g. this post lies under /content/posts/2020-03/include-files-hugo-shortcode/ and then the main file is an index.md. Next to it, I can add resources, which I reference locally and relatively to this main content file. This ensures, that I can easily move a post as a whole (which might include other resources such as images, code, ..) by moving the directory. Now I wanted to embed another markdown or html file into my code, but this seems to not be easily possible by Hugo as of today.
As long as Hugo does not provide functionality to include files from your page bundle, I use the following shortcode as a workaround:
/layouts/shortcodes/include.html :
{{ $base_path := $.Page.Dir }}
{{ $file_path := .Get 0 }}
{{ $full_file_path := (path.Join $base_path $file_path) }}
{{ readFile $full_file_path | markdownify }}
Now, when I want to include HTML, e.g. a table which I keep separate from my blog content, I have a file such as example.html:
<table class="dataframe" border="1">
<thead>
<tr style="text-align: right;">
<th>col0</th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>2</td>
<td>A</td>
<td>B</td>
<td>C</td>
<td>6</td>
<td>7</td>
</tr>
</tbody>
</table>
This can then be easily included by:
{{<include example.html>}}
Result:
col0 | col1 | col2 | col3 | col4 | col5 | col6 |
---|---|---|---|---|---|---|
1 | 2 | A | B | C | 6 | 7 |
However, there are two important notes:
- Hugo warns with
Page.Dir is deprecated and will be removed in a future release. Use .File.Dir
although.File.Dir
can not be used within a shortcode (I am using Hugo v0.68.3). - You can only use markdownifiable content in the included file, thus HTML or markdown. Any Hugo commands or Shortcodes are not further processed and thus deeper nesting is not possible, currently.