Skip to content

Instantly share code, notes, and snippets.

@pdrosos
Last active December 18, 2015 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdrosos/5776107 to your computer and use it in GitHub Desktop.
Save pdrosos/5776107 to your computer and use it in GitHub Desktop.
Typo3 FLOW Fluid template view helper: Array or object access by dynamic key/property/method.
<?php
namespace My\Package\ViewHelpers;
use TYPO3\Flow\Annotations as Flow;
/**
* Allows accessing an array's value by its key or object's property or method by its name
* in order to achieve a "dynamic" path in Fluid, kind of
* {fooarray.{dynamic}}, which is not possible yet, can be replaced
* with {my:objectAccess(haystack: fooarray, needle: key)}
*/
class ObjectAccessViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* @param mixed $haystack
* @param string $needle
* @param string $methodPrefix
* @return mixed
*/
public function render($haystack, $needle, $methodPrefix = null) {
if (is_array($haystack)) {
if (array_key_exists($needle, $haystack)) {
return $haystack[$needle];
} else {
return null;
}
} elseif (is_object($haystack)) {
if (isset($haystack->$needle) || property_exists($haystack, $needle)) {
return $haystack->$needle;
} elseif (method_exists($haystack, $methodPrefix . $needle)) {
return $haystack->{$methodPrefix . $needle}();
}
} else {
return null;
}
}
}
?>
@metaxos
Copy link

metaxos commented Jan 30, 2015

Thank you.
Note: For 6.2 use

extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment