Extracting a YouTube ID from a URL with Twig
I had a client who wanted to embed YouTube videos in their Craft CMS site. It would have been easiest for me to have them only include the YouTube video ID but the sharing box on YouTube gives you a full YouTube URL. You can see that URL in the image at the beginning of this post.
I didn’t want to add any plug-ins to my Craft CMS site to do this so I decided to use the Craft Twig replace filter.
You can use RegEx expressions in the replace filter. I’m only middling when it comes to creating regular expressions but I know enough to get around. In researching around the Internet I came upon the post “How do I get the YouTube video ID from a URL?” on Stack Overflow.
Using bits and pieces from this post I cobble together the following Twig which works fine for my purposes. I’m posting here in case it would be helpful to anyone else.
{% if entry.youTubeUrl %}
{% set ytregex1 = '/^(?:https?:\\/\\/)?(?:www\.)?(?:youtu\.be\\/|youtube\.com)(?:\\/embed\\/|\\/v\\/|\\/watch\\?v=||\\/watch\\\?.+&v=)/' %}
{% set ytregexTrailingSlash = '/(\\/)$/' %}
{% set ytregexTrailingVariables = '/(&+.*)/' %}
{% set youtubeid = youTubeUrl | replace(ytregex1, '') | replace(ytregexTrailingSlash, '') | replace(ytregexTrailingVariables, '') %}
<iframe id="ytplayer" type="text/html" width="540" height="305"
src="https://www.youtube.com/embed/{{ youtubeid }}?autoplay=0&origin={{ siteUrl }}&rel=0"
frameborder="0"></iframe>
{% endif %}
Even better, make it into a macro, something like this that you could just pass in a YouTube URL to.
{# expects some form of YouTube URL #}
{% macro extractYouTubeIdAndProvideiFrame(url) %}
{% set ytregex1 = '/^(?:https?:\\/\\/)?(?:www\.)?(?:youtu\.be\\/|youtube\.com)(?:\\/embed\\/|\\/v\\/|\\/watch\\?v=||\\/watch\\\?.+&v=)/' %}
{% set ytregexTrailingSlash = '/(\\/)$/' %}
{% set ytregexTrailingVariables = '/(&+.*)/' %}
{% set youtubeid = url | replace(ytregex1, '') | replace(ytregexTrailingSlash, '') | replace(ytregexTrailingVariables, '') %}
<iframe id="ytplayer" type="text/html" width="540" height="305" src="https://www.youtube.com/embed/{{ youtubeid }}?autoplay=0&origin={{ siteUrl }}&rel=0" frameborder="0"></iframe>
{% endmacro %}