2014-01-23 26 views
1

我试图做的是我需要对每个数组运行一个数组,如果它没有找到我要查找的数据,它应该采用第一个元素在数组中。TYPO3如果没有任何匹配,请取第一个值

<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> 

我该怎么做?

回答

1

您可以扩展\TYPO3\CMS\Fluid\Core\ViewHelper\AbstractConditionViewHelper并创建您自己的ViewHelper,它在数组中搜索并呈现then/else子级。

创建一个适合您需求的ViewHelper。

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(); 
     } 
    } 

} 

对于下面的示例工作,你控制器应包含以下代码:

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

使用新的视图助手在你的模板列表动作搜索阵列的给定值。

{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> 

由于 '橙色',不包含给定的阵列中,所述新的视图助手呈现ELSE-儿童。要获得阵列的第一个元素,只需使用myarray.0

相关问题