diff --git a/src/Component.php b/src/Component.php index 6c9443d..8a727e8 100644 --- a/src/Component.php +++ b/src/Component.php @@ -240,10 +240,21 @@ private function handleFor( DOMNode $node, array $data ) { list( $itemName, $listName ) = explode( ' in ', $node->getAttribute( 'v-for' ) ); $node->removeAttribute( 'v-for' ); - foreach ( $data[$listName] as $item ) { + if ( preg_match( '/\((?P[^,]+)\s*,\s*(?P[^\)]+)\)/', $itemName, $matches ) ) { + $itemName = $matches['itemName']; + $keyName = $matches['keyName']; + } else { + $keyName = null; + } + + foreach ( $data[$listName] as $key => $item ) { $newNode = $node->cloneNode( true ); $node->parentNode->insertBefore( $newNode, $node ); - $this->handleNode( $newNode, array_merge( $data, [ $itemName => $item ] ) ); + $newData = array_merge( $data, [ $itemName => $item ] ); + if ( $keyName !== null ) { + $newData[$keyName] = $key; + } + $this->handleNode( $newNode, $newData ); } $this->removeNode( $node ); diff --git a/tests/integration/fixture/gloss_widget.html b/tests/integration/fixture/gloss_widget.html index 6d29613..22a3559 100644 --- a/tests/integration/fixture/gloss_widget.html +++ b/tests/integration/fixture/gloss_widget.html @@ -3,14 +3,14 @@
- + diff --git a/tests/integration/fixture/lemma_widget.html b/tests/integration/fixture/lemma_widget.html index 285a249..fe2346d 100644 --- a/tests/integration/fixture/lemma_widget.html +++ b/tests/integration/fixture/lemma_widget.html @@ -7,7 +7,7 @@ {{lemma.language}} -
+
  • diff --git a/tests/php/TemplatingTest.php b/tests/php/TemplatingTest.php index 0d12618..6244613 100644 --- a/tests/php/TemplatingTest.php +++ b/tests/php/TemplatingTest.php @@ -196,6 +196,24 @@ public function testTemplateWithForLoopMustache_RendersCorrectValues() { assertThat( $result, is( equalTo( '

    12

    ' ) ) ); } + public function testTemplateWithForLoopWithIndex_RendersValuesAndIndices() { + $result = $this->createAndRender( + '

    {{index}}: {{item}}

    ', + [ 'list' => [ 10, 20 ] ] + ); + + assertThat( $result, is( equalTo( '

    0: 101: 20

    ' ) ) ); + } + + public function testTemplateWithForLoopWithKey_RendersValuesAndKeys() { + $result = $this->createAndRender( + '

    {{key}}: {{item}}

    ', + [ 'list' => [ 'ten' => 10, 'twenty' => 20 ] ] + ); + + assertThat( $result, is( equalTo( '

    ten: 10twenty: 20

    ' ) ) ); + } + public function testTemplateWithAttributeBinding_ConditionIsFalse_AttributeIsNotRendered() { $result = $this->createAndRender( '

    ', [ 'condition' => false ] );
{{gloss.language}} - + {{gloss.value}} ({{senseId}}) - +