How to break "for loop" in Django template

64,295

Solution 1

There is no break in Django template system. Django template system is not programmed with python but with its own language.

Depending on what you need to do, you might find this question useful. Otherwise, just put the one and only account you are trying to print on HTML on a special field on your RequestContext.

Solution 2

I think you should use slice to achieve your goal

{% for account in object_list|slice:":1" %}

Solution 3

You can't use break statement but you can choose not to print them on html. It's not a best solution but you can use it. I use the following one;

{%for tumbnail in image %}
         {%if tumbnail.object_id == element.id %}
          <img src="/media/{{ tumbnail.image }}" class="tr_all_hover"alt="">

{{ "<!--" }}
  {%endif%} 
{%endfor%}     
{{ "-->" }}

Its basicly seem like this on browser. http://i.stack.imgur.com/MPbR3.jpg

Solution 4

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

Solution 5

     {% 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 %}
Share:
64,295

Related videos on Youtube

tej.tan
Author by

tej.tan

Updated on July 09, 2022

Comments

  • tej.tan
    tej.tan almost 2 years

    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

    • Ismail Badawi
      Ismail Badawi almost 13 years
      Why use a loop if you want to stop after the first iteration? Use {% with account=object_list|first %} ... {% endwith %}
    • Wtower
      Wtower almost 9 years
  • Bobort
    Bobort about 6 years
    Quite clever! And quite helpful!
  • Fatih Komurcuoglu
    Fatih Komurcuoglu about 3 years
    If you use filterset, slicing method result in problem. Most simple and effective way is this.