Code block with readFile in markdown

I have a content file:

~~~ cpp
{{% readfile file="/documents/sample.cpp" %}}

And the readfile shortcode as described in the docs.

This results in an empty <pre> block (i.e., it appears the readfile is ignored completely). If I remove the surrounding ~~~ then the file is included as expected (but not in a code block, of course). If I move the ~~~ into the shortcode itself then the tildes are output verbatim (i.e., no markdown processing into a code block).

Is there a way to include an external file AND have it appear in a code block (that is preferrably syntax highlighted)?

1 Like

Maybe try backticks ``` instead of the tilde ~~~? And no space between the backticks and the language declaration, e.g. ```cpp. And < as well as > instead of %.

See the example from the hugoDocs source:

{{< readfile file="/content/en/readfiles/testing.txt" >}}

(Please ignore the /* and */ in the code example. It’s just not that simple to show a code block example within a code block.)

To show a fenced block with three backticks, surround it with a fence of four backticks.

{{< readfile file="/content/en/readfiles/testing.txt" >}}

Thank you. Edited.

Thanks for the suggestions. I tried them and a few others. Turns out the solution was to remove the cpp tag and then it works as expected. My guess is there’s a bug where reading the tag processes the rest of the code block content in a different way than normal.


{{< file "sample.cpp" >}} <!-- will get format from extension -->

{{< file "" "css" >}} <!-- will get format from 2nd parameter -->

Yes, that works. Thanks a lot.