Lite Youtube Embed for Hugo
Posted on February 13, 2025 • 2 minutes • 407 words
I just read this post on HackerNews regarding why you should not embedding YouTube videos directly. And it got me thinking about how do I do this with Hugo for my blog.
11 years ago, I pretty much did the same thing with Jekyll with my BetterTube plugin and now I want to port it to Hugo.
This is how it work in action:
Note: Clicking the video constitutes your consent to view it via YouTube (including cookies). To view it on the YouTube site instead, please use this link.
Note that Hugo already has a shortcode for embedding YouTube videos . You can use it like this:
{{< youtube 0RKpf3rK57I >}}
But this will be just like embedding YouTube videos directly, unlike what we’re trying to do here. With our solution below, we will only load the video thumbnail at page load. Upon clicking the thumbnail, the video will then be loaded and played. You can compare the two solutions by looking at your browser’s network tab.
How to add it to your Hugo website
-
Create a new file in
assets/css/lite-yt-embed.css
. The content of that file is from lite-yt-embed.css . -
Create a new file in
assets/js/lite-yt-embed.js
. The content of that file is from lite-yt-embed.js . -
Add the following to your
head.html
:
<!-- load lite-youtube css &js if shortcode is used -->
{{ if .HasShortcode "lite-youtube" -}}
{{- $ytCss := resources.Get "css/lite-yt-embed.css" | resources.Fingerprint -}}
{{- $ytJs := resources.Get "js/lite-yt-embed_2024-08-09_v0-3-3.js" | resources.Fingerprint -}}
<link rel="stylesheet" href="{{ $ytCss.RelPermalink }}">
<script src="{{ $ytJs.RelPermalink }}" async></script>
{{- end }}
- Create a new shortcode in
themes/blist/layouts/shortcodes/lite-youtube.html
. The content of that file is like this. Replaceblist
with your theme name.
{{- $videoId := .Get "videoId" -}}
{{- $videoTitle := .Get "videoTitle" -}}
<lite-youtube videoid="{{ $videoId }}" data-bg="url('https://i.ytimg.com/vi/{{ $videoId }}/hqdefault.jpg')"{{ with .Get "params" }} params="{{ . }}"{{ end }}>
<button type="button" class="lty-playbtn">
<span class="lyt-visually-hidden">Play video: {{ $videoTitle }}</span>
</button>
</lite-youtube>
<noscript><p class="ctr legal tight-lead sans-serif"><em>[Video playback capability requires JavaScript to be enabled.]</em></p></noscript>
<p class="ctr legal tight-lead sans-serif lyt-disclaimer"><strong class="red">Note</strong>: Clicking the video constitutes your consent to view it via YouTube (including cookies). To view it on the YouTube site instead, please use <a href="https://www.youtube.com/embed/{{ $videoId }}{{ with .Get "params" }}?{{ . | safeURL }}{{ end }}" rel="noopener">this link</a>.</p>
- Use this in your post like this:
Remove the backticks in the following example because I don’t know how to instruct Hugo not to render the shortcode 🤷🏻♂️
{{< lite-youtube videoTitle="OpenAI's nightmare: Deepseek R1 on a Raspberry Pi" videoId="o1sN1lB76EA" >}}