Random Geekery

Collecting my attempts to improve at tech, art, and life

cover image

Stealing a Hugo Shortcode for Nikola

I needed a YouTube shortcode for Nikola, so I adapted Hugo's.

I keep waffling on whether to switch from Hugo to Nikola or some other static site generator. Meanwhile, my Nikola import spare time project continues. Got the basic structure down, and my theme is almost useful. It even improved the Hugo version of the site.

The shortcode

Some posts included embedded YouTube videos. Nikola’s RST extensions include a youtube directive, but I needed something for the Markdown files. Well, okay. media from the built-in shortcodes would work. I wanted to make a template shortcode, okay?

Here’s what the Hugo shortcode looks like.

{{- $pc := .Page.Site.Config.Privacy.YouTube -}} {{- if not $pc.Disable -}} {{- $ytHost := cond $pc.PrivacyEnhanced "www.youtube-nocookie.com" "www.youtube.com" -}} {{- $id := .Get "id" | default (.Get 0) -}} {{- $class := .Get "class" | default (.Get 1) }} <div {{ with $class }}class="{{ . }}"{{ else }}style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"{{ end }}> <iframe src="https://{{ $ytHost }}/embed/{{ $id }}{{ with .Get "autoplay" }}{{ if eq . "true" }}?autoplay=1{{ end }}{{ end }}" {{ if not $class }}style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" {{ end }}allowfullscreen title="YouTube Video"></iframe> </div> {{ end -}}

I never knew about YouTube privacy configuration for the shortcode. Ah. That’s because it’s not in the shortcode documentation. I like it though. I think I’ll use it.

If you want a Nikola configuration available to your shortcode, add it to conf.py’s `GLOBAL_CONTEXT dictionary.

# Put in global_context things you want available on all your templates.
# It can be anything, data, functions, modules, etc.
"youtube_privacy_enhanced": True,

And here’s shortcodes/youtube.tmpl, adapted for Mako.

<% id = _args[0] root_url = "www.youtube-nocookie.com" if youtube_privacy_enhanced else "www.youtube.com" embed_url = f"https://{root_url}/embed/{id}" style_in_page = "position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;" player_style = "position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" %> <div style="${style_in_page}"> <iframe src="${embed_url}" style="${player_style}" allowfullscreen title="YouTube Video"></iframe> </div>

Not much needed here. It takes the YouTube ID as an argument, picks a host based on youtube_privacy_enhanced, and adds some HTML.

Let’s look at a couple of notes.

Note to self: clicking *play* in a screenshot does nothing

It works!

What Now?

I’m not sure. The Nikola experiment is fun, but I have ideas for the Hugo flow too.