How to break “for loop” in Django template

2.6k Views Asked by At

My code is:

{% for key, value in section.items %}
    {% for key_t, value_t in title.items %}
            {% if value_t.section_id == key|add:"0" %}
                 <li class="nav-item-header"><div class="text-uppercase font-size-xs line-height-xs"> 
                 {{value.title}}</div> <i class="icon-menu" title="Tables"></i></li>
            {% endif %}
    {% endfor %}
{% endfor %}

I want to break the for loop when if the condition is true. like as

{% for key, value in section.items %}
    {% for key_t, value_t in title.items %}
            {% if value_t.section_id == key|add:"0" %}
                 <li class="nav-item-header"><div class="text-uppercase font-size-xs line-height-xs"> 
                 {{value.title}}</div> <i class="icon-menu" title="Tables"></i></li>
            {{break}}
            {% endif %}
    {% endfor %}
{% endfor %}

How is it possible? please help me...

1

There are 1 best solutions below

3
Chris On

There is no way to break out of a for loop in Django Template. However, you can achieve this by setting a variable and adding an if statement on the top like this.

{% set isBreak = False %}
{% for number in numbers %}
{% if 99 == number %}
    {% set isBreak = true %}
{% endif %}

{% if isBreak %}
    {# this is a comment. Do nothing. #}
{% else %}
    <div>{{number}}</div>
{% endif %}
{% endfor %}

for some additional help check out this link https://dev.to/anuragrana/for-loops-in-django-2jdi or check this answer on stack overflow How to break "for loop" in Django template