Search code examples
html-tabletwigcombinationscycle

TWIG: cycle generates any possible combination


I've been faced with the following problem: I'm using TWIG and a foreach loop to generate a html table with content from a database. For a better overview of the table I want to color each 2nd row. Therefore I make use of the cycle function which is provided by twig. My twig template looks like this:

<tbody>
        {% for category in categories %}
            <tr class="gradeA {{ cycle(['even', 'odd'], loop.index0) }}">
                <td class="sorting_1" >
                    {{ category.name }}
                </td>
                <td>
                    {{ category.parent }}   
                </td>
                <td>
                    {% if category.createdAt %}
                        {{ category.createdAt|date('Y-m-d H:i:s') }}
                    {% endif %} 
                </td>
                <td>
                    {% if category.modifiedAt %}
                        {{ category.modifiedAt|date('Y-m-d H:i:s') }}
                    {% endif %} 
                </td>
                <td>
                    <a style="text-decoration: none">
                        <img src="{{ asset('bundles/winpimpcore/images/icons/Axialis-Square-Light-Grey-Png/32x32/Write.png') }}" />
                    </a>
                    <a href="{{ path('_category_delete', { 'id': category.id }) }}" style="text-decoration: none">
                        <img src="{{ asset('bundles/winpimpcore/images/icons/Axialis-Square-Light-Grey-Png/32x32/Trash.png') }}" />
                    </a>
                </td>
            </tr>
        {% endfor %}
    </tbody>

The output which is generated is this (I omit the tr content because it's not relevant):

<tbody>
   <tr class="gradeA odd">
   <tr class="gradeA even">
   <tr class="gradeA even odd">
   <tr class="gradeA odd even">
   <tr class="gradeA odd">
   <tr class="gradeA even">
   <tr class="gradeA even odd">
   <tr class="gradeA even">
</tbody>

So TWIG generates any possible combination of ['even', 'odd'] but what I need is this:

<tbody>
   <tr class="gradeA odd">
   <tr class="gradeA even">
   <tr class="gradeA odd">
   <tr class="gradeA even">
   <tr class="gradeA odd">
   <tr class="gradeA even">
   <tr class="gradeA odd">
   <tr class="gradeA even">
   ...
</tbody>

Am I missing something or even don't I understand the purpose of the cycle function correctly?


Solution

  • you should probably change this line (typo at the end of index)

     <tr class="gradeA {{ cycle(['even', 'odd'], loop.index0) }}">
    

    to

     <tr class="gradeA {{ cycle(['even', 'odd'], loop.index) }}">
    

    I did try it and it works fine.