Ideas, drafts, and hacks

03 Sep 2022

How to embed a YouTube playlist in a Hugo website

Hugo is very flexible to create a static page website, with rich contents. So, one of the things we like to share is YouTube videos, and of course playlists.

To embed a youtube video we can use the following shortcode:

how to embed youtube videos

and the result is as follows:

And for embedding YouTube playlist we need a custom shortcode as this StackOverflow post indicates:

  1. Create: /layouts/shortcodes/youtubepl.html
  2. In that file place the following: (based on the built-in youtube shortcode)
{{- $pc := .Page.Site.Config.Privacy.YouTube -}}
{{- if not $pc.Disable -}}
{{- $ytHost := cond $pc.PrivacyEnhanced  "" "" -}}
{{- $id := .Get "id" | default (.Get 0) -}}
{{- $class := .Get "class" | default (.Get 1) -}}
{{- $title := .Get "title" | default "YouTube Video" }}
<div {{ with $class }}class="{{ . }}"{{ else }}style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"{{ end }}>
 <iframe src="https://{{ $ytHost }}/embed/videoseries?list={{ $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="{{ $title }}"></iframe>
{{ end -}}

And using now this shorthand:

how to embed youtube playlist

We got this result:

Note the list of videos on the top right position.

See you next time.