Display YAML as text

I have a bit of an odd use case where I want to store YAML code examples in YAML files in the data directory. So basically imagine this in data/examples.yaml:

- title: This is example 1
  code:
    foo: bar

What I want is to translate that into HTML like this via shortcode. Here’s the desired output:

This is example 1

foo: bar

And here’s what I tried to do via shortcode:

{{ $title := $example.title }}
{{ $code := $example.code }}
<h2>{{ $title }}</h2>

{{ highlight $code "yaml" "" }}

The trouble, of course, is that Hugo (correctly) interprets $code here as a map to parse rather than as a string to display as YAML and throws an error. I do have a workaround that involves using readFile to read the code in from an external file, but it’d be great to be able to have everything in one big config file, as I envision hundreds of examples like this for this documentation project.

Any ideas? Anyone else run into this? I know it’s an edge case so I’m not hopeful, but you never know with this crew!

I don’t think so. That said, I would recommend you do it a little differently:

  • Store the example yamls inside leaf bundles (possible one big headless bundle if you want everything in one place).
  • Load them via .Resources.Get
  • If you want them as string, just do highlight .Content …
  • If you want them as map, just do transform.Unmarshal .Content

We also have transform.Remarshal that we use for the JSON/YAML/TOML toggles in Hugo Docs.

Thanks a ton for the suggestion, but that unfortunately doesn’t get me beyond the readFile system I had in place previously. In that system I specify a file name in examples.yaml and use readFile $filename to get the corresponding raw YAML content; it works just fine but requires me to spread the examples across a vast array of YAML files. I believe your system works essentially the same way, whereas the goal is to have all the examples and metadata in one YAML file.

It’s admittedly an obscure use case that goes against the grain of Hugo so I’ll just stick with a separate files approach.

Ah, OK – I see. No, that is not currenly possible, but it would be cheap to implement as a template function (transform.Marshal), but you would need to open a GH issue.

1 Like