What I try to do is that I need to run through an array with for each, and if it doesn't find what I am looking for, it should take the first element in the array.

<f:for each="{design.artnumbers}" as="artnumbers" iteration="i">
<f:if {artnumbers.number == 50} >
   do this
</f:if>
</f:for>
<f:if nothing was found>
  take element with i = 1
</f:if>

How can I do that?

有帮助吗?

解决方案

You could extend \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractConditionViewHelper and create your own ViewHelper that does the search in the array and render a then/else child.

Create a ViewHelper that fits your needs.

class SearchArrayViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractConditionViewHelper {

    /**
     * renders <f:then> child if $needle is found in $haystack, otherwise renders <f:else> child.
     *
     * @param string $needle Search value
     * @param array $haystack Array
     * @return string the rendered string
     */
    public function render($needle, $haystack) {
        $found = array_search($needle, $haystack);
        if ($found != FALSE) {
            return $this->renderThenChild();
        } else {
            return $this->renderElseChild();
        }
    }

}

For the following example to work, you controller should contain the following code:

/**
 * List action
 *
 * @return void
 */
public function listAction() {
    $myarray = array('red', 'green', 'blue', 'yellow');
    $this->view->assign('myarray', $myarray);
}

Use the new ViewHelper in your template for the list action to search the array for the given value.

{namespace vh=TYPO3\Test1\ViewHelpers}

<vh:searchArray needle="orange" haystack="{myarray}">
    <f:then>
        Found: Do something
    </f:then>
    <f:else>
        Not found: Do something with first element which is {myarray.0}
    </f:else>
</vh:searchArray>

Since 'orange' is not included in the given array, the new ViewHelper renders the Else-Child. To get the first element of the array, just use myarray.0

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top