Building a TYPO3 extension in Extbase/Fluid
ViewHelper returning multiple values
File paths are relative to the root of your extension /typo3conf/ext/your_extension/
/Classes/ViewHelpers/TestViewHelper.php
<?php
}
namespace VendorName\YourExtension\ViewHelpers;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
class TestViewHelper extends AbstractViewHelper
{
public function initializeArguments()
{
parent::initializeArguments();
/**
* define argument ‘returnVal’ (1st parameter) as ‘string’ (2nd parameter)
* 3rd parameter: describe the argument
* 4th parameter: set argument as required (true) or optional (false, as in this case)
* 5th parameter: is set as default value (‘null’ in this case)
*/
$this->registerArgument('returnVal', 'string', 'A specific value of the array to be returned', false, null);
}
/**
* @return mixed
*/
public function render()
{
$returnArray = [
'a' => 'abcdefg',
'b' => 'hijklmn'
];
$returnVal = $this->arguments['returnVal'];
/**
* returns the full array if returnVal is not given
* returns the string if returnVal is defined and exists as key of the array
* otherwise returns false
*/
if ($returnVal === null) {
return $returnArray;
} elseif (!isset($returnArray[$returnVal])) {
return $returnArray[$returnVal];
} else {
return false;
}
}
}
}
The Fluid Template
/Resources/Private/Templates/…
{namespace someName = VendorName\YourExtension\ViewHelpers}
{dataArray.b}
<p><strong>{someName:test(returnVal: 'a')}</strong></p> <!-- calling by {namespace:viewhelper} and passing the array index as returnVal -->
<f:variable name="dataArray">{someName:test}</f:variable> <!-- calling the full array of data and writing it into fluid variable dataArray -->
<p>
<strong>{dataArray.a}:</strong>
{dataArray.b}
</p> <!-- calling both array elements by their key -->
</p> <!-- calling both array elements by their key -->
This will return:
hijklmn
abcdefg: hijklmn