Hugo shortcode to preview HTML/CSS snippets

As part of a previous post about a fancy CSS shadow effect, I required a way to demonstrate some HTML/CSS on the page, and also render it.

I have a Codepen with the same CSS effect, but embedding it was no option, as I configured strict SCP rules for my website. Besides loading an external website to showcase some HTML/CSS is in theory a bit of an overkill regarding performance.

So I created the following Hugo shortcode which generates a Codepen-like snippet preview without loading any external data.

The source of the shortcode can be found here: github.com/ArcoMul/hugo-shortcode-html-css-preview.

Usage

The shortcode can be initiated in the following format:

{{< snippet >}}
<style>
h1 {
  color: red;
}
</style>
<h1>Hello world!</h1>
{{< /snippet >}}

Which then renders a two small code editors and a preview panel:

<h1>Hello world!</h1>
h1 {
  color: red;
}

The shortcode accepts two named parameters:

  • preview-only="true|false"
    Setting preview-only to false hides the code panels and only shows the preview panel
  • height=Number
    Sets a specific height of the complete element (default 300 pixels)

So the following shortcode format:

{{< snippet preview-only="true" height=100 >}}
...
{{< /snippet >}}

Renders only a preview panel with a height of 100 pixels.

How it works

I implemented this HTML/CSS preview using the srcdoc attribute of an <iframe>. The srcdoc attribute of an <iframe> can be used additionally or instead of to the src attribute (which loads an external url). In the srcdoc HTML code can be defined which will then be rendered as the content of the given <iframe>.

For example the following code shows an iframe with a simple white background and saying “Hi” in the browser default font-family.

<iframe srcdoc="<h1>Hi</h1>"></iframe>

For the shortcode I extract the HTML and CSS from the given shortcode body, and insert them correctly in a simple HTML webpage to be shown in the iframe.

<iframe srcdoc="<html><head><style>{{ $css }}</style></head><body>{{ $html }}</body></html>"></iframe>

Feature completeness

This is of course a very simple alternative compared to a fully functional Codepen embed. To finish up this shortcode the following features would be nice to add:

  • Javascript support
  • Showing HTM/CSS/JS in different tabs to have a better overview
  • Optimize layout for mobile (showing only code or only preview, also using tabs)

Did you use this shortcode? Let me know about it at @ArcoMul.