fighter-ii
fighter-ii

Reputation: 557

Call ViewHelper from Controller

i`m trying to call a ViewHelper Function from within a Controller in Typo3 (to add some additional header data)

Base is the Yag Gallery.

I edited the ItemListController.php and added the following:

$pager = $this->extListContext->getPagerCollection();
$prevLinkUid = $pager->getPreviousPage();
$arg = Tx_YAG_ViewHelpers_Namespace_GPArrayViewHelper::render([page:$prevLinkUid], $pager)
$test = '<link rel="test" href="' . $arg . '">';
$this->response->addAdditionalHeaderData($test);

The addAdditionalHeaderData function works well with other data (e.g. $prevLinkUid, so this part is functioning well).

If i understand the syntax of GPArrayViewHelper::render correctly, i need a pageUid as first argument and the pagerCollection as second argument (derived from this call within Resources/Private/Partials/Pager/Default.html

 <extlist:link.action controller="{controller}" action="{action}" arguments="{extlist:namespace.GPArray(object:'{pagerCollection}' arguments:'page:{pager.previousPage}')}"><span>&lt;</span>       </extlist:link.action>

)

However - if i try this Controller my page won't render, so i assume there is something wrong with the php code / function call, maybe even the syntax of the key value pair/first argument? Sorry, i'm not a professional in php

Any ideas how can i achieve this? I read that it may be difficult to use ViewHelpers from within other controllers?

Upvotes: 0

Views: 2067

Answers (3)

user15104154
user15104154

Reputation: 21

there is a ViewHelperInvoker class which you can use to render a viewhelper in a controller:

    $viewHelperInvoker = GeneralUtility::makeInstance(\TYPO3Fluid\Fluid\Core\ViewHelper\ViewHelperInvoker::class);
    $result = $viewHelperInvoker->invoke(
        \TYPO3\CMS\Fluid\ViewHelpers\Format\CurrencyViewHelper::class,
        [ 'currencySign' => '€' ],
        new \TYPO3\CMS\Fluid\Core\Rendering\RenderingContext(),
        function() {
            return 12345.67;
        }
    );

https://github.com/TYPO3/Fluid/blob/master/src/Core/ViewHelper/ViewHelperInvoker.php

Upvotes: 2

Georg Ringer
Georg Ringer

Reputation: 7939

Please really don't to that. What you can do is using the PageRenderer. E.g. using

$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addHeaderData($headerData);

Upvotes: 0

Mathias Brodala
Mathias Brodala

Reputation: 6460

Viewhelpers are not supposed to be used outside of Fluid templates.

However, there might be an easier way to achieve what you want, e.g. with HeaderAssets. This way you can easily add snippets to the <head> of your page from within a controller action or page template.

Upvotes: 0

Related Questions