djangodjango-templatesdjango-template-filters

How to loop through the multiple items in Django Template


How can I loop through items in django template on the following way

    {% for brand in categories%}
    <div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item1)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item2)
        </figure>
    </div>
    {% endfor %}
    

<div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item3)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item4)
        </figure>
    </div>

<div class="brand-col">
        <figure class="brand-wrapper">
            <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item5)
        </figure>
         <img src="{{brand.product_feature_image.image.url}}" alt="Brand" width="410" height="186" /> (item6)
        </figure>
    </div>

Reference: (item number inside bracket is just for reference) Here, first I want to loop 1 and loop 2 on figure tag and again I want to loop entire div and loop 3 and loop 4 inside the div on figure tag.

I tried to do with cycle, but no luck. Any help will be highly appreciated.


Solution

  • Here is an outline of how this can be achieved. Have an enumerated object in your view function such as

    enumerated_brands = enumerate(categories)
    

    Then pass this object to the context variable in the render method for the return statement of your view function such as:

    def brand_view(request,...):
        ...
        enumerated_brands = enumerate(categories)
        ...
        return render(..., context={'enumerated_brands': enumerated_brands})
    

    Then, use the enumerated_brands in your html file with:

    {% for brand in brands %} 
    {% if forloop.counter0|divisibleby:2 %} 
    <div class="brand-col"> 
    {% endif %} 
    <figure class="brand-wrapper"> 
    <img src="{{brand.product_feature_image.image.url}}" alt="{{brand.name}}" width="410" height="186" /> 
    </figure> 
    {% if forloop.counter|divisibleby:2 or forloop.last %} 
    </div> 
    {% endif %} 
    {% endfor %}