Middleman Helper for Responsive Youtube Videos

I've always hated how YouTube videos look when embedded on my site. They are always the wrong width, letterboxed, or just weird.
After reading this post, I decided to make writing the containing element easier on myself, especially since I write blog posts from my phone or iPad these days.
The finished helper looks like this and accepts a normal (non-embed) youtube watch link:
youtube("https://www.youtube.com/watch?v=boro0iyBjjM")
Because this is a ruby helper, any blog post that uses it will have to have the .erb
file extension so that the ruby server will parse it.1
Here's the helper:
def youtube(url)
@video_id = URI.decode_www_form(URI(url).query).to_h["v"]
concat %{
<div class="youtube-container">
<iframe
width="100%"
height="100%"
src="https://www.youtube.com/embed/#{@video_id}"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
}
end
Here's the corresponding CSS:
.youtube-container {
height: 0;
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
overflow: hidden;
iframe, object, embed {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
}
And here's the final result!
youtube("https://www.youtube.com/watch?v=j2_dJY_mIys")
Transforms into:
Now that I think about it, I could re-implement this as a Vue component, and then it would not depend on having .erb
at the end of the file… but this works. I could also write shortcuts or Drafts actions to insert the correct HTML, but whatever. It works. Enough over optimizing, back to writing!
Fun fact: this post started as a copy/paste of the git commit for the change (Literally git show | pbcopy
-> Drafts.app). Now I'm thinking about writing a transformation script that changes a git show
into a postable markdown blog post... 🤔
-
I started down the path of registering a custom renderer for
RedCarpet
and then decided that I was being overly clever. ↩
Changelog
-
2023-03-13 13:40:24 -0500fix typo
-
2022-06-08 11:31:29 -0500Rename articles
-
2022-06-08 10:48:02 -0500Remove erb extensions
-
2022-06-07 17:35:04 -0500Move youtube helper to admonition
-
2021-01-12 09:50:09 -0600Fix code example
-
2021-01-12 09:44:42 -0600new post: responsive youtube videos