简体   繁体   中英

How do I do nested loops in Django?

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>

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

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM