readFile plus syntax highlighting


I use Hugo mostly for documentation. One thing that I would love to be able to do is to use readFile to pull in code files from outside the Markdown document and have the pulled-in code properly syntax highlighted. But at the moment this doesn’t seem to be possible in Hugo because Chroma doesn’t “see” that material as highlightable. Have any of you found a way around this?

To provide a more concrete example, I would love for something like this to work:

<!-- layouts/shortcodes/code.html -->
<div class="highlight">
    <code class="language-python">
      {{ readFile (.Get 0) }}

But it seems that the stage of the page building cycle at which Chroma operates doesn’t allow for it.

Now, I am aware that this should be possible using Highlight.js or another client-side highlighter. But it would be great to have native support for it in Hugo.

If this doesn’t seem to be possible, I’d also love pointers on how this could be made possible in Hugo. I’d be happy to do that work.


There should be examples of this in the source for the gohugoio website, in short something ala:

 {{ highlight (readFile (.Get 0)) "python" "" }}

The API for the highlight template func is a little bit clumsy, but it works.

That said, it’s worth to note that the readFile func isn’t cached, so you use the same file in many places it may want to look at creating a headless bundle with your “example files” – or maybe use resources.Get.


Beautiful. Just what I was hoping for. I’d gotten so used to using code fences that I completely forgot about the highlight shortcode.