Hugo embed HTML in Markdown
By Flavio Copes
Learn how to embed raw HTML inside Markdown in Hugo after the switch to Goldmark by enabling the unsafe renderer option in your config file.
To embed raw HTML in Markdown with Hugo, enable the unsafe option of the Goldmark renderer in your config file. Without it, Hugo strips the HTML from the rendered page.
Here’s how I ran into this.
After the longest time I switched to the default Hugo markdown rendered, Goldmark, from Blackfriday. I delayed the switch for the longest time but in version 0.100 they removed the old markdown rendered that was deprecated.
Unfortunately this meant all my embedded HTML in markdown stopped working.
How do you know this is your problem?
The symptom is easy to spot. Your Markdown files build fine, but wherever you had HTML, the page shows nothing.
Look at the generated page source and you’ll find this comment in place of your markup:
<!-- raw HTML omitted -->
That’s Goldmark telling you it dropped the HTML on purpose. By default it refuses to render raw HTML, as a security precaution. If your site rendered Markdown submitted by strangers, an attacker could inject a <script> tag.
For a personal blog where you write all the content yourself, there’s nothing unsafe about it. You wrote the HTML, you can trust it.
The fix
I solved this by enabling this option in my config.yaml:
markup:
goldmark:
renderer:
unsafe: true
or, in config.toml:
[markup.goldmark.renderer]
unsafe = true
Rebuild the site and every <div>, <iframe> and inline <img> you had in your Markdown files renders again. No changes needed in the content files themselves.
An alternative: shortcodes
If the same HTML block appears in many posts, a Hugo shortcode can be a nicer solution than raw HTML.
Say you embed YouTube videos often. Hugo ships a built-in shortcode for that:
{{< youtube dQw4w9WgXcQ >}}
Shortcodes render through templates, so they work even with unsafe turned off. You also get one place to update the markup later, instead of hunting through old posts.
For one-off HTML here and there, though, flipping unsafe on is the practical fix.
One thing to be careful with: the setting is per-site. If you build the same content in another Hugo project, or someone clones your theme without your config, the HTML silently disappears again. The <!-- raw HTML omitted --> comment is the clue to look for.
To quickly test how a snippet of markdown (with embedded HTML) renders, try my free markdown preview.