SuperGeekery: A blog probably of interest only to nerds by John F Morton.

A blog prob­a­bly of inter­est only to nerds by John F Mor­ton.

Extracting a YouTube ID from a URL with Twig

Share-Youtube-Video-Url

I had a client who want­ed to embed YouTube videos in their Craft CMS site. It would have been eas­i­est for me to have them only include the YouTube video ID but the shar­ing box on YouTube gives you a full YouTube URL. You can see that URL in the image at the begin­ning of this post.

I did­n’t want to add any plug-ins to my Craft CMS site to do this so I decid­ed to use the Craft Twig replace fil­ter.

You can use RegEx expres­sions in the replace fil­ter. I’m only mid­dling when it comes to cre­at­ing reg­u­lar expres­sions but I know enough to get around. In research­ing around the Inter­net I came upon the post How do I get the YouTube video ID from a URL?” on Stack Over­flow.

Using bits and pieces from this post I cob­ble togeth­er the fol­low­ing Twig which works fine for my pur­pos­es. I’m post­ing here in case it would be help­ful to any­one 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 bet­ter, make it into a macro, some­thing 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 %}