How to use multiple objects in a single Django template for loop?

298 views Asked by At

I have a div element with container class like this :

<div class="container">
    <div class="col-lg-4 col-sm-4">
        <a href=""><h3></h3></a>
        <p></p>
        <span class="label {% cycle 'label-success' 'label-primary' 'label-info' %}"></span>
    </div>
</div>

As you can see from my code, If I do a foor loop on inner div then each row should display 3 items. And span tag must have a different class attribute for each object.

It will be something like this :

<div class="container">
    {% for source_code in all_source_codes %}
    <div class="col-lg-4 col-sm-4">
        <a href=""><h3>{{ source_code.program_title }}</h3></a>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum, dolor officia esse, voluptas harum numquam corporis dolorem! Voluptatem inventore, atque in dolores velit, totam, assumenda dolorum cupiditate esse corporis aspernatur!</p>
        <span class="label {% cycle 'label-success' 'label-primary' 'label-info' %}">{{ source_code.programming_language }}</span>
    </div>
    {% endfor %}
</div>

But this cause grid-view system to crash. So how can I do that ? my focus here is on span tag. I want to display objects with proper class.

Correct Form (this is what I want to be) :

Correct Form

Incorrect Form (this is what it is right now):

Incorrect Form

** UPDATED ** Correct code (for better practice) :

{% for sc in all_source_codes %}
    {% if forloop.first or forloop.counter|add:"-1"|divisibleby:3 %}<div class="container">{% endif %}
        <div class="col-lg-4 col-sm-4">
            <hr style="border: 1px dotted black;">
            <a href="{% url 'detail' sc.pk %}"><h4>{{ sc.program_title }}</h4></a>
            <p>{{ sc.description }}</p>
            <span class="label {% cycle 'label-success' 'label-primary' 'label-info' %}">{{ sc.programming_language }}</span>
        </div>
    {% if forloop.counter|divisibleby:3 or forloop.last %}</div>{% endif %}
{% endfor %}
0

There are 0 answers