如果我必须实现这样的事情,我会在 PHP 控制器的某个地方执行,如下所示:
// In the controller:
$ticketsEnAttente = array_filter($tickets,
function($ticket) {
return $ticket['statut'] === 'En attente';
}
);
return $this->render('my_template.html.twig', [
'tickets_en_attente' => $ticketsEnAttente,
]);
然后在 Twig 中显示计数和不同的票是微不足道的,例如:
<div>
{{ tickets_en_attente | length }} tickets en attente:
</div>
{% for ticket in tickets_en_attente %}
{{ loop.index }}
<div class="d-flex justify-content-start">
<a href="{{ path('ticket', {id:ticket.id}) }}" class="list-group-item list-group-item-action active">
<i class="fas fa-ticket-alt"></i>
{{ ticket.getNomProduit }}
</div>
</a> {# NOTE: there is an html error in your code, </div> and </a> are inverted #}
{% endfor %}
这里唯一的区别是循环索引不会和你给出的原始代码一样,因为它只考虑了过滤后的列表。
一般来说,在树枝模板中放置尽可能少的复杂计算是个好主意。控制器和服务更适合它。
编辑
要回答您的评论,如果有多个状态,您可以创建一个变量,按状态对工单进行分组:
// In your controller:
// Mock data:
$tickets = [
[ 'id' => 1, 'statut' => 'Fermé' ],
[ 'id' => 2, 'statut' => 'En attente' ],
[ 'id' => 3, 'statut' => 'Ouvert' ],
[ 'id' => 4, 'statut' => 'En attente' ],
];
// Group tickets by status:
$ticketsByStatus = [];
foreach ($tickets as $ticket) {
$ticketsByStatus[$ticket['statut']][] = $ticket;
}
// This is equivalent to writing this by hand:
$ticketsByStatus = [
'Fermé' => [
[ 'id' => 1, 'statut' => 'Fermé' ],
],
'En attente' => [
[ 'id' => 2, 'statut' => 'En attente' ],
[ 'id' => 4, 'statut' => 'En attente' ],
],
'Ouvert' => [
[ 'id' => 3, 'statut' => 'Ouvert' ],
],
];
return $this->render('default/index.html.twig', [
'tickets_by_status' => $ticketsByStatus,
]);
然后您可以遍历模板中的每个状态(或者如果您愿意,可以手动访问它们),如下所示:
{% for status in tickets_by_status|keys %}
<h4>{{ status }}:</h4>
<ul>
{% for ticket in tickets_by_status[status] %}
<li>
{{ ticket.id }}
{# {{ ticket.getNomProduit }} #}
</li>
{% endfor %}
</ul>
{% endfor %}
这取决于您自己的需要。