How to get JSON API to TYPO3 Fluid ViewHelper?

Now a days, Headless CMS approach is trending. People love to create APIs based website and webapps. Imaging a situation, where you will need to read JSON API data to your TYPO3 Fluid.

Here is the TYPO3 code snippet to get JSON API data to your TYPO3 CMS using custom TYPO3 Fluid ViewHelper.

Call Custom TYPO3 JSON to Fluid ViewHelper

 


{namespace n=Vendor\Package\ViewHelpers}
<n:JsonToFluid api="https://yoursite/path.json"  />

 

Prepare Custom TYPO3 JsonToFluidViewHelper

 


namespace Vendor\Package\ViewHelpers;

use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;


/**
 * renders the header of the results page
 * @internal
 */
class JsonToFluidViewHelper extends AbstractViewHelper
{
    use CompileWithRenderStatic;

    /**
     * As this ViewHelper renders HTML, the output must not be escaped.
     *
     * @var bool
     */
    protected $escapeOutput = false;

    /**
     * Initialize arguments
     */
    public function initializeArguments()
    {
        $this->registerArgument('api', 'string', '', true);
    }

    /**
     * @param array $arguments
     * @param callable|\Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return array
     */
    public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
    {
        $api = $arguments['api'];
        $req = GeneralUtility::makeInstance(RequestFactory::class);
        $response = $req->request($api,'GET',[]);
        $rawResponse = $response->getBody()->getContents();
        return json_decode($rawResponse, true);
    }
}

Post a Comment

×
Captcha Code Can't read the image? Click here to refresh
  • user
    Gautam January 16, 2023 at 8:31 am
    fffgdgdgdgdg
  • user
    gautam January 16, 2023 at 8:28 am
    dygfuywygweuytruiehfkdjh

Got answer to the question you were looking for?