Reputation: 3556
I'm passing a nested array to my Fluid-Template and now want to iterate over both of them.
Alas, the second for-each only shows the key of the super-array?
The Array (in pseudo-code):
[2016]
[0]
[title]->test
[content]->test
[1]
[title]->test
[content]->test
And the code in my template:
<f:for each="{myArray}" as="topItem" iteration="it1" key="key">
<h4>{key}</h4>
<f:for each="{topItem}" as="subItem" iteration="it2">
{subItem.title}<br />
{subItem.content}
</f:for>
</f:for>
What am I doing wrong?
Upvotes: 1
Views: 1530
Reputation: 4200
Summary of the comments as answer and examples on both mentioned f:for
and f:groupedFor
view-helpers. f:for
is basically good to any kind of array and allows to iterate over each level of nested data - f:group
is good to transfor flat data structures into nested data-sets.
f:for
The input array is two-dimensional and looks like the following
$this->view->assign('nestedItems', [
'2016' => [
['title' => '1st Title', 'content' => '1st Content'],
['title' => '2nd Title', 'content' => '2nd Content'],
],
'2015' => [
['title' => '3rd Title', 'content' => '3rd Content'],
['title' => '4th Title', 'content' => '4th Content'],
],
]);
The Fluid template to iterate over that nested data-set looks like this
<f:for each="{nestedItems}" as="items" key="currentYear">
<h2>{currentYear}</h2>
<f:for each="{items}" as="item">
<h3>{item.title}</h3>
<p>{item.content}</p>
</f:for>
</f:for>
The flat input array looks like this (year is now part of each array element)
$this->view->assign('flatItems', [
['year' => 2016, 'title' => '1st Title', 'content' => '1st Content'],
['year' => 2016, 'title' => '2nd Title', 'content' => '2nd Content'],
['year' => 2015, 'title' => '3rd Title', 'content' => '3rd Content'],
['year' => 2015, 'title' => '4th Title', 'content' => '4th Content'],
]);
The Fluid template to iterate over that nested data-set looks like this
<f:groupedFor each="{flatItems}" as="items" groupBy="year" groupKey="currentYear">
<h2>{currentYear}</h2>
<f:for each="{items}" as="item">
<h3>{item.title}</h3>
<p>{item.content}</p>
</f:for>
</f:groupedFor>
The output is the same in both scenarios
<h2>2016</h2>
<h3>1st Title</h3>
<p>1st Content</p>
<h3>2nd Title</h3>
<p>2nd Content</p>
<h2>2015</h2>
<h3>3rd Title</h3>
<p>3rd Content</p>
<h3>4th Title</h3>
<p>4th Content</p>
Upvotes: 2