-2

I'm trying to output to a Django template one row that has four DIVs:

<div class="row">
   <div class="col-md-3">...</div>
   <div class="col-md-3">...</div>
   <div class="col-md-3">...</div>
   <div class="col-md-3">...</div>
</div>

I need to have two nested For Loops so that each time the fourth DIV is outputted, it will create a new row. In Java, it would be like this:

for(int i = 0; i < object_list.length; i++){
   <div class="row">
      for(int j = 0; j < 4; j++){
         <div class="col-md-3">
      }
}

The code I'm using in the template is:

{% for object in object_list %}
   {% with object|search as search_results %}
      {% if search_results == 'Post' %}
         [need to fill in appropriate HTML]
      {% endif %}
   {% endwith %}
{% endfor %}  

How can I accomplish this?

UPDATE: This didn't exactly use nested for loops, but the below code solved my issue:

     <div class="row">
        {% for object in object_list %}

                {% with object|search as search_results %}
                    {% if search_results == 'Address' %}
                        <div class="col-3">
                            <div class="iq-card">
                                <div class="">{{ user.username }}</div>
                            </div>
                        </div>
                    {% endif %}
                {% endwith %}

        {% endfor %}
    </div>
Jason G
  • 170
  • 1
  • 2
  • 13

2 Answers2

1

You can simply nest for loops in templates the same way you do with simple loops.

{% for object in objects %}
  {% for subobject in object %}
    ...
  {% endfor}
{% endfor %}

For loops with numeric-based iterations, check this question out Numeric for loop in Django templates

michaeldel
  • 2,204
  • 1
  • 13
  • 19
0

For creating multiple <div class="col-md-3">...</div> enclosed by <div class="row"></div> which can also be multiple blocks.

Follow this way:

{% for object in objects %}
    <div class="row">
        {% for subobject in object %}
            <div class="col-md-3">...</div>
        {% endfor}
    </div>
{% endfor %}
Kuldeep
  • 74
  • 4