Working with raw HTML in Hugo

 Sun, 16 Oct 2022 20:54 UTC

Working with raw HTML in Hugo
Image: CC BY 4.0 by cybrkyd

Markdown in Hugo is a fun, fast way to get your content from draft to publication. Markdown has its limits though and sometimes, what you really need is a bit of HTML to add those finishing touches.

From Hugo v0.6.0 onwards, the markdown rendering engine was changed to Goldmark. By default, Goldmark is set to disallow raw HTML. Newbies (read: cybrkyd) will be well-familiar with this comment in their pages:

<!-- raw HTML omitted -->

Here are two ways to work around HTML blocking in Hugo.

Hugo shortcode for raw HTML

This is by far the quickest and easiest way to get Hugo to accept HTML. The only drawback is that you need to call the shortcode every time you want to insert a line of HTML.

Create a new file called rawhtml.html in layouts/shortcodes.

Add the following two lines to rawhtml.html:

<!-- raw html -->

In your markdown file, use the shortcode in the place you want to insert raw HTML.

{{< rawhtml >}}
  <p style="color:green;text-align:center;">Hello World!</p>
{{< /rawhtml >}}

Changing Hugo’s config for HTML rendering

It is possible to enable site-wide HTML rendering in Hugo. This allows HTML to be used without a shortcode.

To enable raw HTML rendering, add the Goldmark settings in the Hugo config file relevant to your theme.

In config.toml add:

  unsafe = true

In config.yaml add:

  unsafe: true

In config.json add:

   "markup": {
      "goldmark": {
         "renderer": {
            "unsafe": true

You can then simply add raw HTML directly into your Markdown file where you need it:

<p style="font-size:24px;color:green;text-align:center;">Hello World!</p>

and have it rendered like this:

Hello World!