nuraska90
nuraska90

Reputation: 27

How to show the first true element after if condition in for loop in django template?

I have a for loop in Django template. After that, I check for coincidences. But in some cases, there are might be 3 coincidences. I need to show only the first coincidence. Now, my code returns the name for 3 times, because, there are 3 coincidences

{% for ip in ips %}
   {% if d.name == ip.name %}
        <strong>{{ d.name}} </strong>                               
   {% endif %}
{% endfor %}

SOLUTION It is impossible to break forloop in django template, so I decided to change in views.py through queryset distinction of similar names

ips = Point.objects.defer('point').order_by('name').distinct('name')

Upvotes: 1

Views: 710

Answers (1)

I don't recommend doing this in Django Template , but in views itself. But if you can't then you can use {{ forloop|break }}.

Something like this :

{% for ip in ips %}
   {% if d.name == ip.name %}
        {{ forloop|break }}
        <strong>{{ d.name}} </strong>                               
   {% endif %}
{% endfor %}

Check the small snippet example here...

Upvotes: 1

Related Questions