I developed this VH which do what you need :
namespace Your\Vendor\ViewHelpers;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Core\Resource\FileRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Frontend\Page\PageRepository;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
/**
* View helper to get the first image of rootline.
*/
class RootlineFirstImageViewHelper extends AbstractViewHelper
{
use CompileWithRenderStatic;
/**
* {@inheritdoc}
*/
public function initializeArguments()
{
$this->registerArgument('pid', 'int', '', true);
}
/**
* {@inheritdoc}
*/
public static function renderStatic(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext
): ?File {
$fileRepository = GeneralUtility::makeInstance(FileRepository::class);
$pages = GeneralUtility::makeInstance(PageRepository::class)->getRootLine($arguments['pid']);
$files = [];
foreach ($pages as $page) {
/** @var FileReference[] $files */
$files = $fileRepository->findByRelation('pages', 'media', $page['uid']);
if (!empty($files)) {
break;
}
}
// It would be nice to have an extra argument to get a random image of the array.
return !empty($files) ? $files[0]->getOriginalFile() : null;
}
}
Then you can call it like this in your Fluid template :
<f:variable name="rootlineFirstImage"><whatever:rootlineFirstImage pid="{data.uid}"/></f:variable>
<f:if condition="{rootlineFirstImage}">
<f:image image="{rootlineFirstImage}" width="1280"/>
</f:if>