作为答案和示例的 cmets 的摘要 f:for 和 f:groupedFor view-helpers。 f:for 基本上适用于任何类型的数组,并允许迭代嵌套数据的每一层 - f:group 非常适合将平面数据结构转换为嵌套数据集。
f:for
输入数组是二维的,如下所示
$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'],
],
]);
用于迭代嵌套数据集的 Fluid 模板如下所示
<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>
f:groupedFor
平面输入数组如下所示(年份现在是每个数组元素的一部分)
$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'],
]);
用于迭代嵌套数据集的 Fluid 模板如下所示
<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>
两种方案的输出
两种情况下的输出是一样的
<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>