---
title: "[FLUID] Zähler/Counter in for-Schleife"
url: "https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife"
source: "typo3.net"
tags: ["Extensions","Extbase","Fluid","Frage","ViewHelper"]
created: "2011-05-18"
last_reply: "2011-05-19"
replies: 9
solved: false
page: 1
pages: 1
lang: "de"
---

# [FLUID] Zähler/Counter in for-Schleife

Extensions › Extbase · 9 Antworten · gestartet 2011-05-18

## Eröffnungsbeitrag

**Unbekannter Benutzer** · 2011-05-18 · [Beitrag #1](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/1)

Hi,

gibt es eine Möglichkeit in einer for-Schleife in Fluid einen Zähler/Counter ausgeben zu lassen?

```html
<f:for each="{objects}" as="obj">
  <div class="content">[COUNTER] - {obj.title}</div>
</f:for>
```

Gewünschte Ausgabe wäre dann in etwa so:

1 - Erstes Objekt
2 - Zweites Objekt
3 - Drittes Objekt
etc.

[COUNTER] müsste dann automatisch pro Schleifendurchlauf hochzählen.

Danke schon mal :)

## Antworten

### [#2](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/2) · xandio · 2011-05-18

Hallo!

Einen Zähler kannst Du folgendermaßen ausgeben lassen:

```html
<f:for each="{objects}" as="obj" iteration="objIterator">
  <div class="content">{objIterator.cycle} - {obj.title}
  </div>
</f:for>
```

Viele Grüße,
Xandi

### [#3](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/3) · Unbekannter Benutzer · 2011-05-19

Hi :)

Danke für deine Antwort. Wenn ich das einbaue erhalte ich im Frontend folgende Fehlermeldung

**Tx_Fluid_Core_Parser_Exception: Argument "iteration" was not registered.**

Kann es sein, dass meine fluid Version das nicht unterstützt (Version 1.0.2)?
Ist die neueste Version von fluid abwärtskompatibel oder darf ich dann alle HTML Templates überarbeiten?

Danke schon mal :)

### [#4](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/4) · xandio · 2011-05-19

Hallo!

Ja, das liegt an Deiner Fluid-Version.

Ich weiß nicht genau, wie es mit der Kompatibilität aussieht, aber einen Versuch ist es sicher wert.

Viele Grüße,
Xandi

### [#5](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/5) · Unbekannter Benutzer · 2011-05-19

Hmm ok, sehr riskant hehe ;)

Wo kann ich die neueste Version herunterladen?

### [#6](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/6) · xandio · 2011-05-19

Ich würde den Extension Manager verwenden. "Retrieve/Update" und danach "Check for extension updates" aufrufen.

Übrigens: ein Auszug aus dem ChangeLog von Fluid:

-------------
Changes for 1.3.0 Alpha 1
=========================
included in TYPO3 4.5.0 Alpha 1.

[...]

* The <f:for>-ViewHelper has now Iteration Information available, if you want that:
  <f:for each="{objects}" as="object" iteration="iteration">
     {iteration.index} is a counter which starts at 0
     {iteration.cycle} is a counter which starts at 1
-------------

### [#7](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/7) · Unbekannter Benutzer · 2011-05-19

Ich hab mittlerweile die Version 1.2.1 (BETA) installiert und es funktioniert irgendwie nicht, Also, meine Extension generiert keine Ausgabe mehr. Ich denke ich bleibe erst Mal bei der alten 1.0.2 Version und programmiere einen ViewHelper für den Zähler (geht das überhaupt?).

Kann ich irgendwo einsehen wie diese "iteration" Funktion implentiert wurde?

Mal sehen wie weit ich komme hehe ;)

Nochmals Danke! :)

### [#8](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/8) · xandio · 2011-05-19

Die render-Methode des ForViewHelpers von Fluid 1.3 müsstest Du Dir anschauen. Falls Du auf 1.3 nicht updaten kannst, dann eben aus einem TYPO3 4.5 extrahieren. Danach den 1.0er-ForViewHelper erweitern und render() überschreiben. Aber sonderlich ratsam ist das nicht. ;-)

### [#9](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/9) · Unbekannter Benutzer · 2011-05-19

Ok, das werde ich mir mal anschauen! Wieso ist das nicht ratsam? Kann ich nicht parallel zum existierenden ForViewHelper meinen eigenen im eigenem Namespace machen?

Das Problem ist halt, es wurden schon einige Extensions mit Extbase 1.0.2 und Fluid 1.0.2 entwickelt. Fluid 1.3 kann ich nur installieren, wenn ich auch Extbase update und ich hab keine Ahnung was passiert wenn ich das mache (hier heruntergeladen -> <http://sourceforge.net/projects/typo3xdev/files/T3X/coreprojects/mvc/>).

### [#10](https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife/10) · Unbekannter Benutzer · 2011-05-19

Es funktioniert! Das is ja mal richtig cool! :D

Das hab ich gemacht (Fluid Version 1.0.2 voraussgesetzt)

Den Ordner "my_extension/Classes/ViewHelpers" anlegen
Im Verzeichnis "ViewHelpers" die Datei "ForViewHelper.php" anlegen
Den Inhalt aus dem Fluid ViewHelper "ForViewHelper.php" kopieren und "iteration"-Funktionalität aus dem ViewHelper aus Fluid 1.3 übernehmen

```php
<?php

/*                                                                        *
 * This script belongs to the FLOW3 package "Fluid".                      *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License as published by the *
 * Free Software Foundation, either version 3 of the License, or (at your *
 * option) any later version.                                             *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * Loop view helper which can be used to interate over array.
 * Implements what a basic foreach()-PHP-method does.
 *
 * = Examples =
 *
 * <code title="Simple Loop">
 * <f:for each="{0:1, 1:2, 2:3, 3:4}" as="foo">{foo}</f:for>
 * </code>
 * <output>
 * 1234
 * </output>
 *
 * <code title="Output array key">
 * <ul>
 *   <f:for each="{fruit1: 'apple', fruit2: 'pear', fruit3: 'banana', fruit4: 'cherry'}" as="fruit" key="label">
 *     <li>{label}: {fruit}</li>
 *   </f:for>
 * </ul>
 * </code>
 * <output>
 * <ul>
 *   <li>fruit1: apple</li>
 *   <li>fruit2: pear</li>
 *   <li>fruit3: banana</li>
 *   <li>fruit4: cherry</li>
 * </ul>
 * </output>
 *
 * @version $Id: ForViewHelper.php 1734 2009-11-25 21:53:57Z stucki $
 * @package Fluid
 * @subpackage ViewHelpers
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3 or later
 * @api
 * @scope prototype
 */
class Tx_MyExtension_ViewHelpers_ForViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {

  /**
   * Iterates through elements of $each and renders child nodes
   *
   * @param array $each The array or SplObjectStorage to iterated over
   * @param string $as The name of the iteration variable
   * @param string $key The name of the variable to store the current array key
   * @param boolean $reverse If enabled, the iterator will start with the last element and proceed reversely
   * @param string $iteration The name of the variable to store iteration information (index, cycle, isFirst, isLast, isEven, isOdd)
   * @return string Rendered string
   * @author Sebastian Kurfürst <sebastian@typo3.org>
   * @author Bastian Waidelich <bastian@typo3.org>
   * @author Robert Lemke <robert@typo3.org>
   * @api
   */
  public function render($each, $as, $key = '', $reverse = FALSE, $iteration = NULL) {
    $output = '';
    if ($each === NULL) {
      return '';
    }
    if (is_object($each)) {
      if (!$each instanceof Traversable) {
        throw new Tx_Fluid_Core_ViewHelper_Exception('ForViewHelper only supports arrays and objects implementing Traversable interface' , 1248728393);
      }
      $each = $this->convertToArray($each);
    }

    if ($reverse === TRUE) {
      $each = array_reverse($each);
    }
    
	$iterationData = array(
		'index' => 0,
		'cycle' => 1,
		'total' => count($each)
	);
  
    $output = '';
    foreach ($each as $keyValue => $singleElement) {
      $this->templateVariableContainer->add($as, $singleElement);
      if ($key !== '') {
        $this->templateVariableContainer->add($key, $keyValue);
      }
      if ($iteration !== NULL) {
        $iterationData['isFirst'] = $iterationData['cycle'] === 1;
        $iterationData['isLast'] = $iterationData['cycle'] === $iterationData['total'];
        $iterationData['isEven'] = $iterationData['cycle'] % 2 === 0;
        $iterationData['isOdd'] = !$iterationData['isEven'];
        $this->templateVariableContainer->add($iteration, $iterationData);
        $iterationData['index'] ++;
        $iterationData['cycle'] ++;
      }
      $output .= $this->renderChildren();
      $this->templateVariableContainer->remove($as);
      if ($key !== '') {
        $this->templateVariableContainer->remove($key);
      }
      if ($iteration !== NULL) {
        $this->templateVariableContainer->remove($iteration);
      }
    }
    return $output;
  }

  /**
   * Turns the given object into an array.
   * The object has to implement the Traversable interface
   *
   * @param Traversable $object The object to be turned into an array. If the object implements Iterator the key will be preserved.
   * @return array The resulting array
   * @author Bastian Waidelich <bastian@typo3.org>
   */
  protected function convertToArray(Traversable $object) {
    $array = array();
    foreach ($object as $keyValue => $singleElement) {
      $array[$keyValue] = $singleElement;
    }
    return $array;
  }
}

?>
```

Im View (z.B: list.html) ganz oben folgende Zeile für den neuen Namespace einfügen

```php
{namespace myext=Tx_MyExtension_ViewHelpers}
```

Dann kann man im View den eigenen ViewHelper wie folgt nutzen

```php
<myext:for each="{objects}" as="obj" iteration="objIteration">
<p>{objIteration.cycle}</p>
</myext:for>
```

:)

---

Quelle: „[FLUID] Zähler/Counter in for-Schleife“, typo3.net, https://www.typo3.net/d/105439-fluid-zaehlercounter-in-for-schleife
Beiträge von Mitgliedern des Forums. Bitte mit Link auf die Diskussion zitieren.
