TYPO3  7.6
ForViewHelper.php
Go to the documentation of this file.
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers;
3 
4 /* *
5  * This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
6  * *
7  * It is free software; you can redistribute it and/or modify it under *
8  * the terms of the GNU Lesser General Public License, either version 3 *
9  * of the License, or (at your option) any later version. *
10  * *
11  * The TYPO3 project - inspiring people to share! *
12  * */
13 
62 {
74  public function render($each, $as, $key = '', $reverse = false, $iteration = null)
75  {
76  return static::renderStatic(
77  $this->arguments,
79  $this->renderingContext
80  );
81  }
82 
90  public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext)
91  {
92  $templateVariableContainer = $renderingContext->getTemplateVariableContainer();
93  if ($arguments['each'] === null) {
94  return '';
95  }
96  if (is_object($arguments['each']) && !$arguments['each'] instanceof \Traversable) {
97  throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('ForViewHelper only supports arrays and objects implementing \Traversable interface', 1248728393);
98  }
99 
100  if ($arguments['reverse'] === true) {
101  // array_reverse only supports arrays
102  if (is_object($arguments['each'])) {
103  $arguments['each'] = iterator_to_array($arguments['each']);
104  }
105  $arguments['each'] = array_reverse($arguments['each']);
106  }
107  if ($arguments['iteration'] !== null) {
108  $iterationData = array(
109  'index' => 0,
110  'cycle' => 1,
111  'total' => count($arguments['each'])
112  );
113  }
114 
115  $output = '';
116  foreach ($arguments['each'] as $keyValue => $singleElement) {
117  $templateVariableContainer->add($arguments['as'], $singleElement);
118  if ($arguments['key'] !== '') {
119  $templateVariableContainer->add($arguments['key'], $keyValue);
120  }
121  if ($arguments['iteration'] !== null) {
122  $iterationData['isFirst'] = $iterationData['cycle'] === 1;
123  $iterationData['isLast'] = $iterationData['cycle'] === $iterationData['total'];
124  $iterationData['isEven'] = $iterationData['cycle'] % 2 === 0;
125  $iterationData['isOdd'] = !$iterationData['isEven'];
126  $templateVariableContainer->add($arguments['iteration'], $iterationData);
127  $iterationData['index']++;
128  $iterationData['cycle']++;
129  }
130  $output .= $renderChildrenClosure();
131  $templateVariableContainer->remove($arguments['as']);
132  if ($arguments['key'] !== '') {
133  $templateVariableContainer->remove($arguments['key']);
134  }
135  if ($arguments['iteration'] !== null) {
136  $templateVariableContainer->remove($arguments['iteration']);
137  }
138  }
139  return $output;
140  }
141 }