[Answered ]-Django: Forloop Counter 0 divisible by 3 not working properly

1👍

Problem When using {% if forloop.counter0|divisibleby:3 %} it doesn’t seem to properly divide out? I can’t quite tell what’s going on.

The forloop.counter0 will count with 0, 1, 2, 3, …. This means that the first cycle will already satisfy the condition, since 0 is dividably by 3 (and by any number), so it will already apply the "split logic" for the first cycle. forloop.counter on the other hand will count with 1, 2, 3, 4, … so the first iteration where it will add a line is the third one.

You can work with:

<table>
    <tr>
    {% for job in jobsite %}
        <td>{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</td>
        {% if forloop.counter|divisibleby:3 and not forloop.last %}
            </tr><tr>
        {% elif not forloop.last %}
            <td class="spacer" rowspan="0">&nbsp;</td>
        {% endif %}
    {% endfor %}
    </tr>
</table>

0👍

I did not find a solution to this specific challenge, however I redesigned it primarily relying on CSS instead of table layout. Code as follows "solves" the challenge.

{% for job in jobsite %}
    <div class="address-label">{{ job.name }}<br/>{{ job.address }}<br/>{{ job.address_2 }}{% if job.address_2 %}<br/>{% endif %}{{ job.city }}, {{ job.state }} {{ job.zip }}</div>
{% endfor %}

Leave a comment