Search code examples
typo3fluidtypo3-9.x

YouTube id contents in TYPO3 Flux FAL Object


I have a YouTube Video as a FAL Object and i need the YouTube id in my Fluid Template.

In a FileReference Object it is possible to get the id via {file.contents}.

But i can't find the YouTube id in the FAL Array from a flux:field.inline.fal In my flux Content Template i get the Video FAL Array like this:

{v:content.resources.fal(field: 'settings.falimage', record:record) -> v:iterator.first() -> v:variable.set(name: 'image')}

In the recieved Array i only find the url to the YouTube Video. Is there a getter or ViewHelper for that?

My Setup:

  • TYPO3 9.5.9

  • Flux 9.2.0

  • VHS 5.2.0


Solution

  • After the failed attempt to use the VHS PregMatchViewHelper (https://fluidtypo3.org/viewhelpers/vhs/development/Variable/PregMatchViewHelper.html) in conjunction with the pattern https://gist.github.com/ghalusa/6c7f3a00fd2383e5ef33 i ended up creating an own ViewHelper that finds the YouTube id from an url:

    <?php
    
    use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
    use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
    use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
    
    
    /**
     * A view helper for rendering the YouTube Id from an url
     *
     * = Examples =
     *
     * <code>
     * {nc:youTubeId(url: 'https://www.youtube.com/watch?v=zpOVYePk6mM')}
     * </code>
     * <output>
     * zpOVYePk6mM
     * </output>
     */
    class YouTubeIdViewHelper extends AbstractViewHelper
    {
        use CompileWithRenderStatic;
    
        /**
         * Initialize arguments
         */
        public function initializeArguments()
        {
            $this->registerArgument('url', 'string', 'YouTube url', true);
        }
    
        /**
         * @param array $arguments
         * @param \Closure $renderChildrenClosure
         * @param RenderingContextInterface $renderingContext
         * @return string youtube id
         */
        public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
        {
            $url = $arguments['url'];
            preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
            $youtube_id = $match[1];
    
            return $youtube_id;
        }
    }