[Answered ]-Django – place differently every second item in for loop

2πŸ‘

βœ…

Other thing you can do to avoid sending 2 additional arrays is to use divisibleby in this manner.

<div class="col-xs-6">
        <ul class="list-unstyled">
         {% for user in users %}
            {% if not forloop.counter|divisibleby:2 %}
                <li><a href="#">{{ user }}</a>
                </li>
            {% endif %}
         {% endfor %}
        </ul>
    </div>

    <div class="col-xs-6">
        <ul class="list-unstyled">
             {% for user in users %}
                {% if forloop.counter|divisibleby:2 %}
                  <li><a href="#">{{ user }}</a>
                  </li>
                {% endif %}
             {% endfor %}
        </ul>
    </div>
πŸ‘€badiya

0πŸ‘

EDIT: I figured it out, after two days of trying it just came to me. If anybody is dealing with the same problem; I handled it in views:

def index(request):
    users = User.objects.all()
    odd_users = users[::2]
    even_users = users[1::2]
    return render(request, 'index.html', {'users': users, 'odd_users': odd_users, 'even_users': even_users})

And then i just loaded it in template:

<div class="col-xs-6">
        <ul class="list-unstyled">
         {% for user in odd_users %}
            <li><a href="#">{{ user }}</a>
            </li>
         {% endfor %}
        </ul>
    </div>

    <div class="col-xs-6">
        <ul class="list-unstyled">
             {% for user in even_users %}
            <li><a href="#">{{ user }}</a>
            </li>
             {% endfor %}
        </ul>
    </div>

Cheers!

πŸ‘€BaltimoreGG

Leave a comment