Rein Van Leirsberghe Rein Van Leirsberghe - 17 days ago 66
Twig Question

Twig foreach group by date

I have a table with football matches called 'matches'. In that table there is a field 'kickoff', which is a datetime-column of the time when the match starts. With the following code I get all the matches out of the table.

$matches = $em->createQueryBuilder()
->from('FootballWcBundle:Matches', 'm')
->addOrderBy('m.kickoff', 'ASC')

return $this->render('FootballWcBundle:Page:matches.html.twig', array(
'matches' => $matches

Now I want to show the matches on the screen grouped by the date.
Like this:








Is there a way to let Twig know to group by the kickoff column or is there another way to do this?

Answer Source

You could do that as below:

    {% set date = null %}
    {% for match in matches %}
        {% if date != match.kickoff %}
            {% set date = match.kickoff %}
            <h3>{{ date }}</h3>
        {% endif %}

        <p>{{ }}</p>
    {% endfor %}

In this way, you set the first date as null, and you iterate all matches and write a 'p' tag with the name (I supposed the match had a name to do the example), and when the date of the matches changes, you write a 'h3' tag with the date of the match. As date is set to null in the first iteration, the first date will be write.