Using Hugo shortcodes in readfile

I’m trying to make use of the readFile shortcode (copied the shortcode from the Hugo Docs repo) and it works great for the needs we have. However, when I try to include a link to another page in the readfile, it doesn’t work.

For example, say I have [link text]({{<ref "another-doc.md">}}) inside of a readfile. That readfile lives in /content/pages/readfiles/read-file-sample.md.

I pull that readfile into a page located at /content/pages/info/happy-page.md.

When I render that page in Hugo, the link becomes localhost:1313/page/info/%7B%7B%3Crelref%20%another-doc.md%22%3E%7D%7D

For some reason, it doesn’t process the Hugo ref shortcode.

I’ve tried changing this to relref, using the near full page (i.e., /pages/info/another-doc.md), nothing works. I did manage to get it working by hardcoding the full page in a regular markdown link, but that makes it more difficult in the future for maintenance of content, which is likely to change quite frequently.

Is there a way to make the readfile render the hugo shortcodes? It’s proving to be a serious limitation as we can’t use any shortcodes in a readfile as none of them render correctly.

or

Hmmm…I tried this, and it doesn’t work. Running Hugo 0.55.6.

If the file I’m trying to read is in the same directory, it works fine. However, I have all the files I’m trying to read in a different folder, and I can’t get it to find that.

For example: The page with the call to get a readfile is in /content/pages/category/page-name.md. The file I’m trying to read lives in /content/pages/readfiles/read-file.md. And that files’ content won’t display at all using the shortcode provided. I tried setting the path value to the direct path, just the file name (which is dangerous since we’ll have files with the same names in different directories).

After reading more in the docs (yes, I started there and struggled first), I think I chased down the solution. The problem I had was that my directory where all the readfiles are located is a headless bundle. I had to use the following:

{{ $file := .Get 0 }}

{{ $path := .Site.GetPage "/headless/bundle/index.md" }}
{{ $reusablePages := $path.Resources.Match $file }}

{{ range $reusablePages }}
    {{ .Content}}
{{ end }}

The documentation wasn’t very clear that you need to use the headless bundles index.md in the .GetPage call. After that, it’s just a matter of matching the file name. So in the above, all I pass to $file is the file name, e.g., my-read-file.md

That seems to work.

1 Like

@maiki, thank you for pointing out that example. I wouldn’t have gotten this sorted without that assistance.

1 Like