Some twig filters to manipulate YouTube video ids and embed codes


« Back to overview

Here are some twig filters to handle Youtube, for example in Craft CMS or Symfony templating.

  • Extract YouTube id from a YouTube url
  • Create embed urls with options such as autoplay
  • Create preview image url's for YouTube

Extract YouTube id

Extract a YouTube url from an embed url

    public function getFilters()
    {
        return [
            'my_extract_youtube_id' => new \Twig_SimpleFilter('my_extract_youtube_id', [$this, 'myExtractYoutubeId'])
        ];
    }

    /**
     * Extract youtube id from embed / youtube urls like
     * https://www.youtube.com/watch?v=tT3hyLvYNNo,
     * https://www.youtube.com/embed/tT3hyLvYNNo
     * Also accepts an id only.
     *
     * @param $url
     * @return boolean|string
     */
    public function myExtractYoutubeId($url)
    {
        $parsed = parse_url($url);
        $path = $parsed['path'] ?? false;
        $host = $parsed['host'] ?? false;
        $pathParts = $path ? explode('/', $path) : [];
        $queryString = $parsed['query'] ?? '';
        parse_str($queryString, $query);

        // handle direct id's like 'tT3hyLvYNNo'
        if (!$host && count($pathParts) === 1) {
            return $pathParts[0];
        }
        // handle https://www.youtube.com/watch?v=tT3hyLvYNNo
        if (isset($query['v'])) {
            return $query['v'];
        }
        // handle https://www.youtube.com/embed/tT3hyLvYNNo
        if ('embed' === ($pathParts[1] ?? '') && count($pathParts) > 2) {
            return $pathParts[2] ?? false;
        }
        return false;
    }

Generate a YouTube embed url from a YouTube id

Generates an embed code, specify several options such as autoplay


twig filter YouTube embed url

    public function getFilters()
    {
        return [
            'my_youtube_embed_url' => new \Twig_SimpleFilter('my_youtube_embed_url', [$this, 'myYoutubeEmbedUrl'])
        ];
    }

    /**
     * Compose a youtube embed url, specify options such as autoplay
     * @param $youtubeId
     * @param array $options
     * @return string
     */
    public function myYoutubeEmbedUrl($youtubeId, $options = [])
    {
        // see: https://developers.google.com/youtube/player_parameters
        static $defaults = [
            'rel' => false,                 // show related from all channels or from own channel
            'autoplay' => false,            // set to true or false. note that for autoplaying, mute needs to be set to true
            'mute' => false,                // set to true or false.
            'enablejsapi' => false,         // set to true or false.
        ];
        $options = array_merge($defaults, $options);
        $params = [
            'rel' => (int)$options['rel'] ? '1' : '0',
            'autoplay' => (int)$options['autoplay'] ? '1' : '0',
            'mute' => (int)$options['mute'] ? '1' : '0',
            'enablejsapi' => (int)$options['enablejsapi'] ? '1' : '0',
        ];
        $parts = [];
        foreach ($params as $k => $v) {
            $parts[] = rawurlencode($k) . '=' . rawurlencode($v);
        }
        return 'https://www.youtube.com/embed/' . rawurlencode($youtubeId) . '?' . implode('&', $parts);
    }

Get YouTube thumbnail/preview images from a YouTube id

Get preview urls from YouTube for a YouTube id, specify a quality such as sd, mq, hq, maxres.


twig filter get YouTube preview urls
  public function getFilters()
    {
        return [
            'my_youtube_thumb' => new \Twig_SimpleFilter('my_youtube_thumb', [$this, 'myYoutubeThumb'])
        ];
    }

    /**
     * Returns a video thumbnail from youtube
     * quality is one of: sd, mq, hq, maxres
     * @param $youtubeId
     * @param $quality
     * @return string
     */
    public function myYoutubeThumb($youtubeId, $quality)
    {
        return 'https://img.youtube.com/vi/' . rawurlencode($youtubeId) . '/' . rawurlencode($quality) . 'default.jpg';
    }