Fluid模板中按月份分组年度事件:日期变更时如何输出月标题?
按月份分组事件的实现方案
首先得确保你的事件列表是按日期排序的,这是分组能正常工作的前提——如果列表乱序,月份标题会断断续续出现。你可以在后端的Repository里添加排序逻辑,比如:
// 在你的 OperationRepository.php 中 public function findAllSortedByBeginDate() { $query = $this->createQuery(); $query->setOrderings([ 'begin' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING ]); return $query->execute(); }
然后在控制器里调用这个方法,把排序后的列表传递给模板。
接下来修改Fluid模板,用临时变量跟踪当前月份,每当月份变化时输出标题:
{# 初始化临时变量,用来记录当前显示的月份 #} <f:variable name="currentMonth" value="" /> {# 遍历排序后的事件列表 #} <f:for each="{operations}" as="operation"> {# 仅当事件有日期时处理分组逻辑 #} <f:if condition="{operation.begin}"> {# 把当前事件的日期格式化为「月份+年份」的字符串,比如 "Januar 2024" #} <f:format.date format="F Y" date="{operation.begin}" as="eventMonth" /> {# 如果当前事件的月份和之前记录的不一样,输出月份标题并更新临时变量 #} <f:if condition="{eventMonth} != {currentMonth}"> <h2>{eventMonth}</h2> <f:variable name="currentMonth" value="{eventMonth}" /> </f:if> </f:if> {# 这里保留你原来的事件内容代码 #} <f:link.action action="show" arguments="{operation:operation}" pageUid="{settings.operationSinglePid}"> <table> <tr> <td width="70px">[{operation.number}]</td> <td width="170px"> <f:if condition="{operation.begin}"> {operation.begin -> f:format.date(format:'d.m.Y, H:i \U\h\r')} </f:if> </td> <td width="260px">Stichwort: <f:for each="{operation.type}" as="stichwort"> {stichwort.title} </f:for> </td> <td width="300px"> <f:if condition="{operation.location}"> <span>{operation.location}</span> </f:if> </td> </tr> </table> </f:link.action> </f:for>
细节说明
- 日期格式
F Y会输出本地化的月份全称+年份(比如德语的Januar 2024),如果想要更简洁的格式可以改成m.Y(输出01.2024)。 - 临时变量
currentMonth用来记录当前已经输出过的月份,避免重复打印标题。 - 加了
<f:if condition="{operation.begin}">的判断,防止没有日期的事件导致格式化出错。
内容的提问来源于stack exchange,提问作者Evilmachine
相关产品推荐
相关产品推荐

