How to break "for loop" in Django template

Viewed 67934

I have this code

    {% for account in object_list %}
        <tr>
        {% for field, value in book.get_fields %}
              <th>{{ field.verbose_name }}</th> 
        {% endfor %}
        </tr>
    {{ break }}
    {% endfor %}

I want to break the for loop after first iteration. break is not working

9 Answers
     {% for i in list %}
      {% if forloop.counter < 11 %}                                     
        <tr>
          <td>{{ forloop.counter }}</td>
          <td>{{ i.product__name }}</td>
          <td>{{ i.brand__name }}</td>
          <td>{{ i.country__name}}</td> 
          <td>{{ i.city__name}}</td>  
                     
        </tr>
      {% endif %} 
             
      {% endfor %}

You can use your Django template system for loop in javascript for loop as inner loop and can use break as follows :-

for(var i=0;i<1;i++){
        {% for owner in Owner %}
            id  = "{{owner.id}}";
            if(id == pk1){
                f="{{owner.flat}}";
                break;
            }             
        {% endfor %}
     }

In this case you can check if forloop.counter == 1 or if forloop.first and simply print that first item.

  {% for account in object_list %}
      {% if forloop.first %}
        <tr>
        {% for field, value in book.get_fields %}
              <th>{{ field.verbose_name }}</th> 
        {% endfor %}
        </tr>
      {% endif %}
    {% endfor %}

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.)

1- Use with to define a variable to determine current status,

2- Use a template custom tag to change statement to negate current status.

in template use like this:

{% with statement=1 %}
   {% for obj in listObject %}
       {% if ifStatement and statement %}
           {% changeStatement statement as statement %} // when u don't want to enter in if again.
           Do your job here!!
       {% endif %}
   {% endfor %}
{% endwith %}

In template custom tags :

@register.simple_tag
def changeStatement(status):
    return not status
Related