Skip to main content

The Name's Burns. Ken Burns...

·424 words·2 mins
Mayke Web Hugo Bling
Martin Hamilton
Author
Martin Hamilton
Futurist and innovation advisor. ADHD. Hacker. Solarpunk.

Bling up your web pages with a little help from a Hugo shortcode!

Fed up of all those tired off-the-shelf themes and same-y looking websites? Maybe it’s time to spice things up a bit!

If you’re using a Static Site Generator like Hugo or Jekyll, it can be surprisingly easy to make big changes to your site.

Like maybe loading random images as your page backgrounds and then subjecting your readers to the eponymous Ken Burns panning and zooming effect?

Would that be wrong? No, surely not! It must be the (now sadly traumatised) readers who are wrong.

Why, it could be as simple as adding one line to the Markdown code for a page:

{{< kenburns urls="cat1.jpg,cat2.jpg,cat3.jpg" >}}
Warning! This is a lie. He is lying to you.

OK, it’s not quite that simple. Especially if you haven’t tangled with the inner workings of an SSG before.

But it’s not too far off.

First you’ll need a bit of CSS to do the Magical-Ken-Burnsy-Bits. Through a process of trial and error, search engines and the powerful copy/paste function, I arrived at this (default cats are optional):

@keyframes kenburns {
    0% { transform: scale(1); opacity: 0.3; }
    50% { transform: scale(1.2); opacity: 0.3; }
    100% { transform: scale(1); opacity: 0.3; }
}

.kenburns-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-image: url('/img/optional-default-cats.jpg');
    background-size: cover;
    background-position: center;
    z-index: -1;
    animation: kenburns 15s infinite alternate ease-in-out;
}

On my Hugo installation this is added to assets/css/custom.css, the CSS theme customisations which are inserted as part of each page build.

Then you need to create need something called a shortcode, which becomes a “command” that you can call from your Markdown. My kenburns shortcode looks like this:

{{- $images := split (.Get "urls") "," -}}
{{- $bgid := .Get "bgid" | default "kenburns-background" -}}

<div id="{{ $bgid }}" class="{{ $bgid }}"></div>

<script>
    const images = [
        {{ range $images }}"{{ . }}",{{ end }}
    ];
    const randomImage = images[Math.floor(Math.random() * images.length)];
    document.getElementById("{{ $bgid }}").style.backgroundImage = `url('${randomImage}')`;
</script>

The shortcode above takes two parameters - bgid is the ID to use for the HTML element that the image will be inserted into - kenburns-background by default to match the CSS. Then there’s urls, a comma delimited list of the images to pick from.

On my Hugo installation this is added to layouts/shortcodes/kenburns.html, at which point it becomes possible to use it as a shortcode in pages or even add it to the master page template.

As if anyone would ever do such a thing…