jinja2nunjuckstemplating-engine

Jinja2 / Nunjucks: Different treatment to for-loop elements


I have a list:

list = [a, b, c, 1, 2, 3, a, b, c, 1, 2, 3, a, b, c, 1, 2, 3]

And I want to show it as a table, where every 4th, 5th & 6th element is styled in its own way, e.g like this.:

<td><span class="label label-info">1</span></td>
<td><span class="label label-danger">2</span></td>
<td><span class="label label-primary">3</span></td>

I am batching the list into 6er rows to display it as a table like this:

{%- for row in list|batch(6, '&nbsp;') %}
    <tr>
    {%- for column in row %}
        <td>{{ column }}</td>
    {%- endfor %}
    </tr>
{%- endfor %}

But I have no idea how to do what I described above. Anybody have an idea?


Solution

  • You can use loop.index to tell which number an iteration is at in a loop:

    {%- for row in list|batch(6, '&nbsp;') %}
        <tr>
        {%- for column in row %}
            <td>
                {%- if loop.index == 4 %}<span class="label label-info">{% endif -%}
                {%- if loop.index == 5 %}<span class="label label-danger">{% endif -%}
                {%- if loop.index == 6 %}<span class="label label-primary">{% endif -%}
                {{ column }}
                {%- if loop.index in [4, 5, 6] %}</span>{% endif -%}
            </td>
        {%- endfor %}
        </tr>
    {%- endfor %}